User defined and custom exceptions in Java

Java 8Object Oriented ProgrammingProgramming

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

 Live Demo

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

 Live Demo

import java.util.Arrays;
import java.util.Scanner;
public class AIOBSample {
   public static void main(String args[]){
      int[] myArray = {1254, 1458, 5687,1457, 4554, 5445, 7524};
      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

 Live Demo

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

 Live Demo

import java.util.Enumeration;
import java.util.Vector;
public class EnumExample {
   public static void main(String args[]) {
      //instantiating a Vector
      Vector<Integer> vec = new Vector<Integer>( );
      //Populating the vector
      vec.add(1254);
      vec.add(4587);
      //Retrieving the elements using the Enumeration
      Enumeration<Integer> 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.

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(){
   return " MyException [Message of your exception]";
}

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……….){
   throw ex;
}

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.

 Live Demo

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 <= 'z')) {
            return false;
         }
      }
      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.

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.<init>(CustomCheckedException.java:25)
at july_set3.CustomCheckedException.main(CustomCheckedException.java:41)
raja
Published on 06-Sep-2019 15:20:48
Advertisements