Java Reference
In-Depth Information
Self-Test Exercises
(continued)
8. In the code given in Self-Test Exercise 3 , what is the
catch
block?
9. In the code given in Self-Test Exercise 3 , what is the
catch
block parameter?
10. Is the following legal?
Exception exceptionObject =
new
Exception("Oops!");
11. Is the following legal?
Exception exceptionObject =
new
Exception("Oops!");
throw
exceptionObject;
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 example,
in Display 9.4, we have defined an exception class called
DivisionByZeroException
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
contains. However, the class does inherit all the methods of the class
Exception
.
1
I n
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:
constructors
super
("Division by Zero!");
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
1
Some programmers would prefer to derive the
DivisionByZeroException
class from the pre-
defined 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
exceptions. 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.