Java-User Defined Exception

User Defined Exception

You can create your own exception by extending Exception class. The throw keyword are used while implementing user defined exceptions. Following program demonstrates the use of a user-defined subclass of Throwable class. Note that Exception is a subclass of Throwable and therefore MyOwnException is a subclass of Throwable class. An object of a class that extends Throwable can be thrown and caught.

Program

final

Program Source

class MyOwnException extends Exception {
    
    MyOwnException(String msg)
    {
        super(msg);
    }
}

class Javaapp {

    public static void main(String[] args) {
        
        try{
            int age = 130;
            if(age>=100)
            {
                throw new MyOwnException("Age = "+age+" It's not possible");
            }
        }catch(MyOwnException ex)
        {
            System.out.println(ex);
        }
        System.out.println("Execution Complete");
    }
}

Leave a Comment