Custom Exceptions in Java | Exception Handling Part – 4

In this java programming tutorial, we will study and understand how to make custom exceptions in java. Before we start of with this topic, you can checkout the Part 1 of Exception handling where we discussed the overall concept of Exception handling and how it works in Java. Click here to go the article.

If you are creating your own Exception that is known as custom exception or user-defined exception. Java custom exceptions are used to customize the exception according to user need. By the help of custom exception, you can have your own exception and message.

Java provides us facility to create our own exceptions which are basically derived classes of Exception. Thus there is inheritance involved when creating custom exceptions.

Writing your own exception class

Now, let’s see how to create a custom exception in action. Here are the steps:

  • Create a new class whose name should end with Exception like ClassNameException. This is a convention to differentiate an exception class from regular ones.
  • Make the class extends one of the exceptions which are subtypes of the java.lang.Exception class. Generally, a custom exception class always extends directly from the Exception class.
  • Create a constructor with a String parameter which is the detail message of the exception. In this constructor, simply call the super constructor and pass the message.

Let’s see a simple example of java custom exception.

class InvalidAgeException extends Exception{  
 InvalidAgeException(String s){  
  super(s);  
 }  
}
class TestCustomException1{  
  
   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...");  
  }  
}

Output –

Output:Exception occured: InvalidAgeException:not valid
       rest of the code...

Leave a Reply

Your email address will not be published. Required fields are marked *