Java Reference
In-Depth Information
In the first form, causeExc is the exception that causes the current exception. That is,
causeExc is the underlying reason that an exception occurred. The second form allows
you to specify a description at the same time that you specify a cause exception. These
two constructors have also been added to the Error , Exception , and RuntimeException
classes.
The chained exception methods added to Throwable are getCause( ) and initCause( ) .
These methods are shown here:
Throwable getCause( )
Throwable initCause(Throwable causeExc )
The getCause( ) method returns the exception that underlies the current exception. If
there is no underlying exception, null is returned. The initCause( ) method associates
causeExc with the invoking exception and returns a reference to the exception. Thus, you
can associate a cause with an exception after the exception has been created. In general,
initCause( ) is used to set a cause for legacy exception classes that don't support the two
additional constructors described earlier.
Chained exceptions are not something that every program will need. However, in cases
in which knowledge of an underlying cause is useful, they offer an elegant solution.
Creating Exception Subclasses
Although Java's built-in exceptions handle most common errors, Java's exception handling
mechanism is not limited to these errors. In fact, part of the power of Java's approach to ex-
ceptions is its ability to handle exception types that you create. Through the use of custom
exceptions, you can manage errors that relate specifically to your application. Creating an
exception class is easy. Just define a subclass of Exception (which is, of course, a subclass
of Throwable ). Your subclasses don't need to actually implement anything—it is their ex-
istence in the type system that allows you to use them as exceptions.
The Exception class does not define any methods of its own. It does, of course, inherit
those methods provided by Throwable . Thus, all exceptions, including those that you cre-
ate, have the methods defined by Throwable available to them. Of course, you can over-
ride one or more of these methods in exception subclasses that you create.
Here is an example that creates an exception called NonIntResultException , which is
generated when the result of dividing two integer values produces a result with a fractional
component. NonIntResultException has two fields which hold the integer values; a con-
structor; and an override of the toString( ) method, allowing the description of the excep-
tion to be displayed using println( ) .
Search WWH ::




Custom Search