Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – User defined exception subclasses

Beside exception classes defined by Java, we can generate our own exception class that is a subclass of an Exception class.

For that, we just need to inherit Exception class or its any subclass in the class to which we want to make user defined exception type.

Inheriting Exception class, inherits Throwable class automatically.

It depends on the need that which class should be extended by user defined class.

Example

import java.util.Scanner;

class NotEvenException extends Exception 
{

}

class Test 
{
    public static void check(int num) throws NotEvenException
    {
        if(num%2 == 0)
        {
            System.out.println("Entered Number is even");
        }
        else
        {
            throw new NotEvenException(); 
        }
    }
}

class UserDefExcepDemo 
{
    public static void main(String args[]) 
    {
        System.out.println("Enter any number");
        Scanner in = new Scanner(System.in);
        int num = in.nextInt();
        in.close();
        try
        {
            Test.check(num);
        } 
        catch(NotEvenException e)
        {
            System.out.println("Exception handled");
        }		
    }
}

Output

If the number entered is even

Enter any number
6
Entered Number is even

If the number entered is odd

Enter any number
7
Exception handled

Here we have created NotEvenException as a user defined exception that extends Java’s built in class called Exception.

 

Leave a reply