Java Reference
In-Depth Information
In fact, there are at least two cases where these two examples would have different effects:
A finally clause is executed even if a return statement is executed in the try or catch blocks.
If an exception is thrown in the try block but not caught, then the finally clause is still executed.
In the latter case, the uncaught exception could be an unchecked exception that does not require
a catch block, for instance. However, it could also be a checked exception that is not handled
by a catch block but propagated from the method, to be handled at a higher level in the call
sequence. In such a case, the finally clause would still be executed.
It is also possible to omit the catch blocks in a try statement that has both a try block and a
finally clause if the method is propagating all exceptions:
try {
Protect one or more statements here.
}
finally {
Perform any actions here common to whether or not
an exception is thrown.
}
12.6
Defining new exception classes
Where the standard exception classes do not satisfactorily describe the nature of an error condition,
new, more-descriptive exception classes can be defined using inheritance. New checked exception
classes can be defined as subclasses of any existing checked exception class (such as Exception ),
and new unchecked exceptions would be subclasses of the RuntimeException hierarchy.
All existing exception classes support the inclusion of a diagnostic string passed to a construc-
tor. However, one of the main reasons for defining new exception classes is to include further
information within the exception object to support error diagnosis and recovery. For instance,
some methods in the address-book application, such as changeDetails , take a key parameter
that should match an existing entry. If no matching entry can be found, then this represents a
programming error, as the methods cannot complete their task. In reporting the exception, it
is helpful to include details of the key that caused the error. Code 12.15 shows a new checked
exception class that is defined in the address-book-v3t project. It receives the key in its con-
structor and then makes it available through both the diagnostic string and a dedicated accessor
method. If this exception were to be caught by an exception handler in the caller, the key would
be available to the statements that attempt to recover from the error.
Code 12.15
An exception class with
extra diagnostic
information
/**
* Capture a key that failed to match an entry
* in the address book.
*
* @author David J. Barnes and Michael Kölling.
* @version 2011.07.31
*/
 
 
Search WWH ::




Custom Search