How to write custom exception in Java?

devquora
devquora

Posted On: Feb 22, 2018

 

A custom exception is also known as a user-defined exception are derived classes of Java Exception classes. In order to create your Custom exception in Java following point must be taken care of.

  • 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.

Custom exception example in Java

class InvalidAgeException extends Exception{  
 InvalidAgeException(String s){  
  super(s);  
 }  
}  

class CustomExceptionTest{  
  
   static void validate(int age)throws InvalidAgeException{  
     if(age<18)  
      throw new InvalidAgeException("not valid");  
     else  
      System.out.println("welcome to vote");  
   }  
     
   public static void main(String args[]){  
      try{  
      validate(13);  
      }catch(Exception m){System.out.println("Exception occured: "+m);}  
  
      System.out.println("rest of the code...");  
  }  
} 

Above is an example of a custom exception in Java that checks the age of voter. If age is less than 18 years than it throws an InvalidAgeException.

    Related Questions

    Please Login or Register to leave a response.

    Related Questions

    Cyient Java developer Interview Questions

    List types of storage classes in java?

    There are basically four types of storage classes in Java:Automatic storage class: When a variable that is used in the coding is defined within a function and that also with the auto specifier the...

    Cyient Java developer Interview Questions

    Write a java program to generate Fibonacci series?

    A JAVA program to generate Fibonacci series is as follows: import java.util.Scanner; public class Fibonacci { public static void main(String[] args) { int n, a = 0, b = 0, c = ...

    Cyient Java developer Interview Questions

    How does the garbage collector work in Java?

    Garbage collection is the process of automatically managing memory in java. It is helpful to finds the unused objects that are no longer used by the program and deletes or remove them to free up the m...