Custom Exceptions in Java

Java comes with a feature where we can define our own customized exception. Such an exception once declared, can be used as any pre-defined exception.  Hence, the exception which is created by us suiting our requirement is known as a custom or user-defined exception.

Why Custom Exceptions?

There are certain conditions for which exception does not comes pre-defined. E.g The age of a person is denoted by int/float as per the condition. But, in either of the case, it should not be negative. Age is always a positive number. But no such exception class exists to restrict a negative value to the age holding variable.  Hence we need to create our own exception class, that will handle such an exception.

There are many such real-life/business scenarios where we need to define and use our own exceptions.

To use custom-defined Exception, we need to perform both the steps properly

1. Define your own Exception class

To create our own exception, we need to inherit the Exception class. After extending, we can set the data member message inside the constructor using super(). The message holds the detailed message that resulted in such an exception.

Example:

class MyAgeException extends Exception
{
    public MyAgeException (String message)
    {
        // Calls constructor of the parent class Exception to set detailed message
        super(message);
    }
}

2. Explicitly  throw the Exception

The user-defined exceptions must be thrown manually.

 Example:

throw new MyAgeException("You are under aged !!");

Let us look at an example combining both the steps, to create our first custom exception.

class MyAgeException extends Exception
{
    public MyAgeException (String message)
    {
        super(message);
    }
}


public class ClassMain{
    public static void main(String args[]){
        int age=-6;
        System.out.println("I am before Try Block.");
        try{
            System.out.println("\tI am inside Try Block.");
            if(age<0)
            throw new MyAgeException("\t\tAge cannot be negative.");
            else if (age<18)
            throw new MyAgeException("\t\t<Ineligible>You are under aged.");
            else if (age>=60)
            throw new MyAgeException("\t\t<Ineligible>You are over aged.");
        }
        catch(MyAgeException obj)
        {
            System.out.println(obj.getMessage());
        }
        finally
        {
            System.out.println("\tI am in finally Block.");
        }
        System.out.println("I am the last print statement.");
    }
}

Output:

I am before Try Block.                                                                              
        I am inside Try Block.                                                         
            Age cannot be negative.
        I am in finally Block.                                                             
I am the last print statement.

As we can see that with age as a negative value, the exception was caught and handled.

Similarly, for different values of age, we will have different outputs.

age = 12;
I am before Try Block.                                                                              
        I am inside Try Block.                                                         
           <Ineligible>You are under aged.
        I am in finally Block.                                                             
I am the last print statement.
age = 68;
I am before Try Block.                                                                              
        I am inside Try Block.                                                         
           <Ineligible>You are over aged.
        I am in finally Block.                                                             
I am the last print statement.
age = 43;
I am before Try Block.                                                                              
        I am inside Try Block.                                                         
        I am in finally Block.                                                             
I am the last print statement.

This was an overview of how we can create our own exception. We will discuss Java Threads in the next lecture.