Java Reference
In-Depth Information
Creating Your Own Exception Classes
When you create your own classes or write programs, exceptions are likely to occur. As
you have seen, Java provides a substantial number of exception classes to deal with these
situations. However, it does not provide all the exception classes you will ever need.
Therefore, Java enables programmers to create exception classes to handle the exceptions
not covered by Java's exception classes or to handle their own exceptions. This section
describes how to create your own exception classes.
Java's mechanism to process the exceptions you define is the same as that for built-in
exceptions. However, you must
throw your own exceptions using the throw
statement.
The exception class that you define extends either the class Exception or one of
its subclasses. Also, a subclass of the class Exception is either a predefined class or
a user-defined class. In other words, if you have created an exception class, you can
define other exception classes by extending the definition of the exception class you
created.
Typically, constructors are the only methods that you include when you define your own
exception class. Because the exception class you define is a subclass of an existing
exception class, either built-in or user-defined, the exception class that you define inherits
the members of the superclass. Therefore, objects of the exception classes can use the
public members of the superclasses.
Because the class Exception is derived from the class Throwable , it inherits the
methods getMessage and toString of the class Throwable . These methods are
public , so they are also inherited by the subclasses of the class Exception .
EXAMPLE 11-12
This example shows how to create your own division by the zero exception class.
public class MyDivisionByZeroException extends Exception
{
public MyDivisionByZeroException()
{
super ("Cannot divide by zero");
}
public MyDivisionByZeroException(String strMessage)
{
super (strMessage);
}
}
 
Search WWH ::




Custom Search