User Defined Exception in Java

The built-in exceptions provided by the Java platform are used to handle errors occurring in the program. But , sometimes the programmer wants to create his own application specific exceptions. User defined exception can be created simply by defining a subclass of Exception class and using the throw keyword.

 

class OwnnException extends Exception

{

public OwnnException(String message)

{

System.out.println("Own Exception class constructor");

}

}

public class CreateOwnException

{

public static int divide(int ii,int jj)throws Exception

{

if(jj==0)

throw new OwnnException("This statement is not executed");

return ii/jj;

}

public static void main(String aa[])

{

int ii=70;

int jj=0;

try

{

System.out.println("ii="+ii);

System.out.println("jj="+jj);

System.out.println("divison="+divide(ii,jj));

}

catch(OwnnException oee)

{

System.out.println("Demoninator cannot be zero");

oee.printStackTrace();

}

catch(Exception exc)

{

System.out.println(exc.getMessage());

}

}

}

 CreateOwnException

Explanation..

This example defines a subclass of exception called OwnException. Thus, this class will inherit the methods defined by the Throwable class through Exception class. The CreateOwn Exception class defines a method divide() which throws an object oe of OwnException type when the denominator of the fraction is zero. The printStackTrace() of the Throwable class is overridden to display the message which contains all the information that lead to the error, such as the name of the method, which caused the error, the name of the caller of the method which lead to the error, the line number in which that error has occurred, etc.