Enterprise applications often focus little on Exception Handling During building, which causes low-level exceptions (suchExcessive dependency of java. rmi. RemoteException and javax. naming. NamingException. In this column of EJB best practices, Brett McLaughlin explains why a little attention to exception handling can be of great help to us, two simple technologies are displayed to help you build a more robust and useful Exception Handling framework correctly.
In previous articles in this series, exception handling is not within the scope of the discussion. However, you may find that we have been avoiding low-level exceptions from the Web layer. We provide clients with exceptions such as ApplicationException and InvalidDataException, without letting the Web layer handle exceptions such as java. rmi. RemoteException or javax. naming. NamingException.
Remote and naming exceptions are system-level exceptions, while application and invalid data exceptions are business-level exceptions because they submit more suitable business information. When deciding what type of exception to throw, you should always consider the layer to handle the reported exception first. The Web layer is usually driven by end users who execute business tasks, so it is best to use it to handle business-level exceptions. However, at the EJB layer, you are executing system-level tasks, such as using JNDI or database. Although these tasks will eventually be merged into the business logic, it is better to express them with system-level exceptions such as RemoteException.
Theoretically, you can make all Web Layer Methods anticipate handling and responding to single application exceptions, as we have done in some previous examples. However, this method is not suitable for long running. It is a much better exception handling solution to let your delegate method throw more specific exceptions. Basically, this is more useful for receiving clients. In this article, we will discuss two techniques that will help you create richer and more specific exceptions without generating a large amount of unnecessary code.
Nested exception
When designing a reliable Exception Handling solution, the first thing to consider is to abstract the so-called low-level or system-level exceptions. These core Java exceptions usually report errors in network traffic, JNDI or RMI problems, or other technical problems in applications. RemoteException, EJBException, and NamingException are common examples of low-level exceptions in Enterprise Java programming.
These exceptions have no meaning at all, and are especially confusing when received by clients at the Web layer. If the client calls purchase () and receives a NamingException, it cannot solve the exception. At the same time, application code may need to access the information in these exceptions, so they cannot be easily discarded or ignored.
The answer is to provide a more useful exception, which also contains low-level exceptions. Listing 1 demonstrates a simple ApplicationException designed for this:
Listing 1. nested exception package com. ibm;
Import java. io. PrintStream;
Import java. io. PrintWriter;
Public class ApplicationException extends Exception {
/** A wrapped Throwable */
Protected Throwable cause;
Public ApplicationException (){
Super ("Error occurred in application .");
}
Public ApplicationException (String message ){
Super (message );
}
Public ApplicationException (String message, Throwable cause ){
Super (message );
This. cause = cause;
}
// Created to match the JDK 1.4 Throwable method.
Public Throwable initCause (Throwable cause ){
This. cause = cause;
Return cause;
}
Public String getMessage (){
// Get this exceptions message.
String msg = super. getMessage ();
Throwable parent = this;
Throwable child;
// Look for nested exceptions.
While (child = getNestedException (parent ))! = Null ){
// Get the childs message.
String msg2 = child. getMessage ();
// If we found a message for the child exception,
// We append it.
If (msg2! = Null ){
If (msg! = Null ){
Msg + = ":" + msg2;
} Else {
Msg = msg2;
}
}
// Any nested ApplicationException will append its own
// Children, so we need to break out of here.
If (child instanceof ApplicationException ){
Break;
}
Parent = child;
}
// Return the completed message.
Return msg;
}
Public void printStackTrace (){
// Print the stack trace for this exception.
Super. printStackTrace ();
Throwable parent = this;
Throwable child;
// Print the stack trace for each nested exception.
While (child = getNestedException (parent ))! = Null ){
If (child! = Null ){
System. err. print ("Caused :");
Child. printStackTrace ();
If (child instanceof ApplicationException ){
Break;
}
Parent = child;
}
}
}
Public void printStackTrace (PrintStream s ){
// Print the stack trace for this exception.
Super. printStackTrace (s );
Throwable parent = this;
Throwable child;
// Print the stack trace for each nested exception.
While (child = getNestedException (parent ))! = Null ){
If (child! = Null ){
S. print ("Caused :");
Child. printStackTrace (s );
If (child instanceof ApplicationException ){
Break;
}
Parent = child;
}
}
}
Public void printStackTrace (PrintWriter w ){
// Print the stack trace for this exception.
Super. printStackTrace (w );
Throwable parent = this;
Throwable child;
// Print the stack trace for each nested exception.
While (child = getNestedException (parent ))! = Null ){
If (child! = Null ){
W. print ("Caused :");
Child. printStackTrace (w );
If (child instanceof ApplicationException ){
Break;
}
Parent = child;
}
}
}
Public Throwable getCause (){
Return cause;
}
}
The code in Listing 1 is simple; we have simply "stringed" multiple exceptions to create a single, nested exception. However, the real benefit is that this technology is used as the starting point to create an application-specific exception hierarchy. The exception hierarchy allows the EJB client to receive both business-specific exceptions and system-specific information without writing a large amount of additional code.
Exception hierarchy
The exception hierarchy should start with some very robust and Common exceptions, such as ApplicationException. If you make the top-level exception too specific, the result is that you will have to reconstruct the hierarchy in the future to adapt to some common situations.
Therefore, let us assume that your application requires NoSuchBookException, InsufficientFundsException, and SystemUnavailableException. You do not need to create these three exceptions to inherit ApplicationException, And then you only need to provide a few necessary constructors to create formatted messages. Listing 2 is an example of such an exception hierarchy:
Listing 2. Exception hierarchies package com. ibm. library;
Import com. ibm. ApplicationException;
Public class NoSuchBookException extends ApplicationException {
Public NoSuchBookException (String bookName, String libraryName ){
Super ("The book" + bookName + "was not found in the" +
LibraryName + "library .");
}
}
When you need to write a large number of special exceptions, the exception hierarchy greatly simplifies the work. For an exception, adding one or two constructors for each exception class takes a few minutes. You also often need to provide subclasses for these more specific exceptions (these exceptions are also subclasses of the main application exceptions) to provide more specific exceptions. For example, you may need InvalidTitleException and BackorderedException to inherit NoSuchBookException.
Enterprise applications usually do not pay attention to Exception Handling During building. Although low-level exceptions (such as RemoteException and NamingException) are easy (and sometimes attractive), if you build a reliable and well-thought-out exception model from the beginning, then you will spend less energy on the application. Creating a nested, hierarchical exception framework improves code readability and availability.