User defined error in java

User defined and custom exceptions in Java

Certain exceptions are prompted at compile time they are known as Checked exceptions or, compile-time exceptions and, exceptions that occur at run-time are known as run time exceptions or, unchecked exceptions. Such cases are known as exceptions when an exception occurs the program gets terminated abnormally.

User defined and custom exceptions in Java

An exception is an issue (run time error) that occurred during the execution of a program. For understanding purpose let us look at it in a different manner.

Generally, when you compile a program, if it gets compiled without a .class file will be created, this is the executable file in Java, and every time you execute this .class file it is supposed to run successfully executing each line in the program without any issues. But, in some exceptional cases, while executing the program, JVM encounters some ambiguous scenarios where it doesn’t know what to do.

Here are some example scenarios −

  • If you have an array of size 10 if a line in your code tries to access the 11th element in this array.
  • If you are trying to divide a number with 0 which (results to infinity and JVM doesn’t understand how to evaluate it).

Such cases are known as exceptions when an exception occurs the program gets terminated abnormally. Certain exceptions are prompted at compile time they are known as Checked exceptions or, compile-time exceptions and, exceptions that occur at run-time are known as run time exceptions or, unchecked exceptions.

Each possible exception is represented by a predefined class and all these classes are found in the java.lang package. Following are some exception classes

NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException, IllegalArgumentException, IllegalStateException etc…

Example: ArithmeticException

import java.util.Scanner; public class ExceptionExample < public static void main(String args[]) < Scanner sc = new Scanner(System.in); System.out.println("Enter first number: "); int a = sc.nextInt(); System.out.println("Enter second number: "); int b = sc.nextInt(); int c = a/b; System.out.println("The result is: "+c); >>

Output

Enter first number: 100 Enter second number: 0 Exception in thread "main" java.lang.ArithmeticException: / by zero at ExceptionExample.main(ExceptionExample.java:10)

Example: ArrayIndexOutOfBoundsException

import java.util.Arrays; import java.util.Scanner; public class AIOBSample < public static void main(String args[])< int[] myArray = ; System.out.println("Elements in the array are: "); System.out.println(Arrays.toString(myArray)); Scanner sc = new Scanner(System.in); System.out.println("Enter the index of the required element: "); int element = sc.nextInt(); System.out.println("Element in the given index is :: "+myArray[element]); > >

Output

Run time exception −
Elements in the array are: [897, 56, 78, 90, 12, 123, 75] Enter the index of the required element: 7 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7 at AIOBSample.main(AIOBSample.java:12)

Example: ArrayStoreException

import java.util.Arrays; public class ArrayStoreExceptionExample < public static void main(String args[]) < Number integerArray[] = new Integer[3]; integerArray[0] = 12548; integerArray[1] = 36987; integerArray[2] = 555.50; integerArray[3] = 12548; System.out.println(Arrays.toString(integerArray)); >>

Output

Runtime Exception −
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Double at ther.ArrayStoreExceptionExample.main(ArrayStoreExceptionExample.java:9)

Example: NoSuchElementException

import java.util.Enumeration; import java.util.Vector; public class EnumExample < public static void main(String args[]) < //instantiating a Vector Vectorvec = new Vector( ); //Populating the vector vec.add(1254); vec.add(4587); //Retrieving the elements using the Enumeration Enumeration en = vec.elements(); System.out.println(en.nextElement()); System.out.println(en.nextElement()); //Retrieving the next element after reaching the end System.out.println(en.nextElement()); > >

Output

Runtime Exception −
1254 4587 Exception in thread "main" java.util.NoSuchElementException: Vector Enumeration at java.util.Vector$1.nextElement(Unknown Source) at July_set2.EnumExample.main(EnumExample.java:18)

User-defined exceptions

You can create your own exceptions in Java and they are known as User-defined exceptions or custom exceptions.

Читайте также:  Mvc html css js

To create a user-defined exception extend one of the above-mentioned classes. To display the message override the toString() method or, call the superclass parameterized constructor bypassing the message in String format.

MyException(String msg) < super(msg); >Or, public String toString()

Then, in other classes wherever you need this exception to be raised, create an object of the created custom exception class and, throw the exception using the throw keyword.

MyException ex = new MyException (); If(condition……….)

Custom Checked and Custom Unchecked

  • All exceptions must be a child of Throwable.
  • If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.
  • If you want to write a Runtime Exception, you need to extend the RuntimeException class.

Example: Custom Checked exception

Following Java program Demonstrates how to create a Custom checked exception.

import java.util.Scanner; class NotProperNameException extends Exception < NotProperNameException(String msg)< super(msg); >> public class CustomCheckedException< private String name; private int age; public static boolean containsAlphabet(String name) < for (int i = 0; i < name.length(); i++) < char ch = name.charAt(i); if (!(ch >= 'a' && ch > return true; > public CustomCheckedException(String name, int age) < if(!containsAlphabet(name)&&name!=null) < String msg = "Improper name (Should contain only characters between a to z (all small))"; NotProperNameException exName = new NotProperNameException(msg); throw exName; >this.name = name; this.age = age; > public void display() < System.out.println("Name of the Student: "+this.name ); System.out.println("Age of the Student: "+this.age ); >public static void main(String args[]) < Scanner sc= new Scanner(System.in); System.out.println("Enter the name of the person: "); String name = sc.next(); System.out.println("Enter the age of the person: "); int age = sc.nextInt(); CustomCheckedException obj = new CustomCheckedException(name, age); obj.display(); >>

Output

Compile-time exception

On compiling, the above program generates the following exception.

CustomCheckedException.java:24: error: unreported exception NotProperNameException; must be caught or declared to be thrown throw exName; ^ 1 error

Example: Custom unChecked exception

If you simply change the class that your custom exception inherits to RuntimeException it will be thrown at run time

class NotProperNameException extends RuntimeException < NotProperNameException(String msg)< super(msg); >>

If you run the previous program By replacing the NotProperNameException class with the above piece of code and run it, it generates the following runtime exception.

Читайте также:  Python модели временных рядов

Output

Runtime exception
Enter the name of the person: Krishna1234 Enter the age of the person: 20 Exception in thread "main" july_set3.NotProperNameException: Improper name (Should contain only characters between a to z (all small)) at july_set3.CustomCheckedException.(CustomCheckedException.java:25) at july_set3.CustomCheckedException.main(CustomCheckedException.java:41)

Types of Exception in Java with Examples, Java defines several types of exceptions that relate to its various class libraries. Java also allows users to define their own exceptions.

Java custom exceptions

java custom user defined exceptions#java #exceptions #user.
Duration: 10:05

User Defined Exception in Java

Please use the following link to install the Katalon Studio:https://katalon.com/sign-up?getr
Duration: 9:28

How to create custom exceptions in Java?

In this video solution, you’ll see how to create custom exceptions in Java. Java Exception Duration: 7:07

On creating custom exceptions

How are Exceptions in java defined and how can I define my own? As an example, we have ArithmeticException which prohibits us dividing by 0 and does not break the program.

What is try-catch ‘s advantage to catching the same potential error with an if-else logic?

Furthermore, suppose I don’t operate in the field of all integers, but specifically the field Z2 formed under addition in which 1+1=0 .

Provided I have pre-defined an array of logic of operations, were I to do something like this:

public class myError extends Exception < public myError(String e) < super(e); >> 

But then, how does the try-catch clause know it is supposed to catch myError ? What makes myError be what it is? In other words: what defines, for example, ArithmeticException , to look for division by 0 among other things?

Alternatively I could throw new myError(«something’s wrong») , but that would defeat the whole point of defining a «custom» exception to begin with, since I could have thrown any exception like that.

Exceptions are just classes that extend class Throwable . Defining your own exception is done by creating a class that extends Throwable or one of its subclasses.

You can throw your own exception using throw new myError(); .

ArithmeticException is a special exception thrown by the JVM when you divide by zero. It’s not the exception that is looking for places where you divide by zero; it’s how the / works. The / operator checks if the denominator is zero and will then throw the exception.

There is no way to add for example a check to the + operator so that it will throw whatever exception if the result of adding two numbers is zero. You’d have to write your own method to check and do this.

public int add(int a, int b) < int result = a + b; if (result == 0) < throw new myError(); >return result; > // Then use the add() method instead of + try < int a = 1; int b = -1; int result = add(a, b); System.out.println(result); >catch (myError e)

How can we create a custom exception in Java?, User-defined exceptions in Java are also known as Custom Exceptions. Steps to create a Custom Exception with an Example. CustomException class

Читайте также:  Нахождение наименьшего числа питон

Throwing a custom exception instead of other types of exceptions

I have a program in which I want to throw one of 4 exceptions that I define. I get an HTTP response and according its error code I want to throw the exceptions:

public List> getData(String product) < try < Responseresponse = dataApi.dataGet(product).execute(); if (!response.isSuccessful()) < log.error(String.format("Failed to get data for product [%s] error [%s]", product, Util.getErrorMsg(response))); >DataGeneralResponse body = response.body(); return body != null ? body.getData(): null; > catch (Exception e) < log.error(String.format("Failed to get data for product [%s] error[%s]", product, Util.getErrorMsg(response))); >return null; > 

So I need to to something like that in Util:

public void handleResponse(Response response) throws CustomException < switch (response.code()) < case 500: throw new FirstCustomException("); break; case 404: throw new SecondCustomException("); break; default: throw new UnknownCustomException("); >> 

But when I try to remove the catch clause I get unhandled IOException error on the execute method and on the getErrorMsg method.

I get unhandled IOException error on the execute method and on the getErrorMsg method.

This indicates that you have a method, which is trying to throw a checked exception, which is not surrounded by a try catch clause. By Java language standard all methods, which throw checked exceptions must do one of the two ..

  • Be surrounded by a try-catch block which catches the relevant exception
  • Declare that they throw the relevant exception by using the throws keyword

You can use one of the methods above to deal with error you are getting. If this does not completely solve your problem, please add a comment below and I’ll respond.

How to define custom exception class in Java, the easiest way?, No, you don’t «inherit» non-default constructors, you need to define the one taking a String in your class. Typically you use super(message)

Источник

User defined error in java

  • Introduction to Java
  • The complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works – JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?
  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods
  • Access Modifiers in Java
  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java
  • Inheritance in Java
  • Abstraction in Java
  • Encapsulation in Java
  • Polymorphism in Java
  • Interfaces in Java
  • ‘this’ reference in Java

Источник

Оцените статью