Java Reference
In-Depth Information
Defining Exception Classes
A
throw
statement can throw an exception object of any exception class. A common
thing to do is to define an exception class whose objects can carry the precise kinds of
information you want thrown to the
catch
block. An even more important reason for
defining a specialized exception class is so that you can have a different type to identify
each possible kind of exceptional situation.
Every exception class you define must be a derived class of some already defined
exception class. An exception class can be a derived class of any exception class in the
standard Java libraries or of any exception class that you have already successfully
defined. Our examples will be derived classes of the class
Exception
.
When defining an exception class, the constructors are the most important members.
Often there are no other members, other than those inherited from the base class. For exam-
ple, in Display 9.3, we've defined an exception class called
DivisionBy-ZeroException
whose only members are a no-argument constructor and a constructor with one
String
parameter. In most cases, these two constructors are all the exception class definition con-
tains. However, the class does inherit all the methods of the class
Exception
.
1
In particular,
the class
DivisionByZeroException
inherits the method
getMessage
, which returns a
string message. In the no-argument constructor, this string message is set with the following,
which is the first line in the no-argument constructor definition:
super
("Division by Zero!");
constructors
This is a call to a constructor of the base class
Exception
. As we have already noted,
when you pass a string to the constructor for the class
Exception
, it sets the value of a
Display 9.3
A Programmer-Defined Exception Class
1
public class
DivisionByZeroException
extends
Exception
2{
3
public
DivisionByZeroException()
You can do more in an exception
constructor, but this form is
common.
4
{
5
super
("Division by Zero!");
6
}
7
public
DivisionByZeroException(String message)
8
{
super
is an invocation of the constructor
for the base class
Exception
.
9
super
(message);
10
}
11
}
1
Some programmers would prefer to derive the
DivisionByZeroException
class from the predefined
class
ArithmeticException
, but that would make it a kind of exception that you are not required to
catch in your code, so you would lose the help of the compiler in keeping track of uncaught excep-
tions. For more details, see the subsection “Exceptions to the Catch or Declare Rule” later in this
chapter. If this footnote does not make sense to you, you can safely ignore it.