Java custom( user-defined) exception

  • June 24, 2022
  • Java
legacy classes

Because our own exceptions are derived classes of Exception, Java allows us to create them. A custom exception or user-defined exception is one we create on our own. Java custom exceptions are used to tailor the exception to user requirements. A User-Defined Exception, also known as a custom exception, is your own exception class that you create and then throw using the keyword “throw.”

Need for custom exception :
  • To detect a subset of current Java exceptions and give them a particular treatment.
  • Exceptions to business logic These are the business logic and workflow exceptions. Understanding the precise issue is helpful for both application users and developers.

Let’s see a simple example of a Java custom exception. In the following code, the constructor of InvalidAgeException takes a string as an argument. This string is passed to the constructor of the parent class Exception using the super() method. Also, the constructor of the Exception class can be called without using a parameter, and calling super() method is not mandatory.

// class representing custom exception  
class InvalidAgeException  extends Exception  
    public InvalidAgeException (String str)  
        // calling the constructor of parent Exception  
// class that uses custom exception InvalidAgeException  
public class TestCustomException1  
    // method to check the age  
    static void validate (int age) throws InvalidAgeException{    
       if(age < 18){  
        // throw an object of user defined exception  
        throw new InvalidAgeException("age is not valid to vote");      }  
       else {   
        System.out.println("welcome to vote");   
    // main method  
    public static void main(String args[])  
            // calling the method   
        catch (InvalidAgeException ex)  
            System.out.println(" Caught the exception");  
            // printing the message from InvalidAgeException object  
            System.out.println("Exception occured: " + ex);  
        System.out.println("rest of the code...");    
Caught the exception
Exception occured: age is not valid to vote
rest of the code...

Note: also read about the Interface vs Abstract class

Follow Me

If you like my post, please follow me to read my latest post on programming and technology.

Leave a Reply

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