Java Reference
In-Depth Information
System.out.println (e.getMessage() );
}
Notice that the more specific exception is caught first, then the generic excep-
tion. Be sure to execute the logic for the more specific class (the subclass) before
the more generic superclass. If you reverse the order, your more specific logic
won't be executed.
Once in a while, you may need to catch an exception and perform some logic
based on the exception, but still not completely manage the primary reason for the
exception condition. For example, suppose that your TextMessage really needs to
be translated before the application can continue. In this case, you should certainly
write the exception message to a file (to the standard output device in the exam-
ple), but in addition, you may want to inform the end user. To meet these re-
quirements, you can rethrow the exception and allow the calling class to complete
the error-handling logic.
catch (NoDatabaseAvailableException e){
// The exception handler logic.
// This will execute only if getTranslate() creates an exception of type
// NoDatabaseAvailableException.
System.out.println (e.getMessage() );
// Pass the exception to the calling program.
throw e;
}
The last Exception structure is the finally operator. This structure provides a
mechanism to define statements that should execute even if an exception occurs.
Statements in a finally code block will execute after the try block, even if an ex-
ception is caught. So, you can place logic that is always required in the finally
block, and it will always be executed.
The finally block is often used to make sure external resources, such as a
database connection or an open file handle, are in a properly managed condition
at all times.
For example, the getTranslate() function in TextMessage reads a database to
get the translated error text. Suppose that in order to read the database, you need
to get a database connection from a pool of database connections. If you have any
problems reading the database in getTranslate() , you can throw the NoData-
baseAvailableException . However, you still have to manage the connection and re-
turn it to the pool.
Search WWH ::




Custom Search