6.4 Exception Handling
The final
piece in bean-managed persistence is exception handling. The EJB
specification classifies three different exception conditions:
Remote exceptions EJB exceptions Application exceptions
All bean interface methods throw remote
exceptions—java.rmi.RemoteException.
The underlying distributed computing architecture throws a remote
exception whenever something goes wrong with the network. You should
never throw one in your code.
EJB
exceptions—javax.ejb.EJBException—are
signals from your code to the container that something has gone wrong
with the application outside of the normal application states. In the
examples earlier in this chapter, I threw EJB exceptions for database
errors and JNDI errors. As a developer, you should never catch an
EJBException.
Anything that represents a flaw in the application state counts as an
application exception. The container
ignores application exceptions.
From the perspective of database access, your first task is to turn
all data access exceptions into EJB exceptions as shown in the
examples in this chapter. On the other hand, when you check for valid
values, you will throw application exceptions to indicate a failure
to match the required value. In the code to create a book, for
example, I could have added the following check that throws a
CreateException:
if( bookID.longValue( ) < 0L ) {
throw new CreateException("Invalid book ID.");
}
|