Exception handling is particularly relevant to this discussion because, unlike in container-managed persistence, in bean-managed persistence the bean developer is responsible for throwing the correct exceptions at the right moments. For this reason, we’ll take a moment to discuss the different types of exceptions in BMP. This discussion will be useful when we get into the details of database access and implementing the callback methods.
Bean-managed beans throw three types of exceptions:
Application exceptions include standard
EJB application exceptions and custom application exceptions. The
standard EJB application exceptions are
CreateException
,
FinderException
,
ObjectNotFoundException
,
DuplicateKeyException
, and
RemoveException
. These exceptions are thrown from
the appropriate methods to indicate that a business logic error has
occurred. Custom exceptions are exceptions developed for specific
business problems. We cover developing custom exceptions in Chapter 12.
Runtime
exceptions are thrown from the virtual machine itself and indicate
that a fairly serious programming error has occurred. Examples
include the NullPointerException
and
IndexOutOfBoundsException
. These exceptions are
handled by the container automatically and should not be handled
inside a bean method.
You will notice that all the callback methods
(ejbLoad()
, ejbStore()
,
ejbActivate()
, ejbPassivate()
,
and ejbRemove()
) throw an
EJBException
when a
serious problem occurs. All EJB callback methods declare the
EJBException
and
RemoteException
in their throws
clauses. Any exception thrown from one of the callback methods must
be an EJBException
or a subclass. The
RemoteException
type is
included in the method signature to support backward compatibility
with EJB 1.0 beans. Its use has been deprecated since EJB 1.1.
RemoteException
s should never be thrown by
callback methods of EJB 1.1 or EJB 2.0 beans.
Checked exceptions thrown by other
subsystems should be wrapped in an EJBException
or
application exception and rethrown from the method. Several examples
of this can be found in the previous example, in which an
SQLException
that was thrown from JDBC was caught
and rethrown as an EJBException
. Checked
exceptions from other subsystems, such as those thrown from JNDI,
JavaMail, and JMS, should be handled in the same fashion. The
EJBException
is a subtype of the
RuntimeException
, so it doesn’t need to be
declared in the method’s throws
clause. If
the exception thrown by the subsystem is not serious, you can opt to
throw an application exception, but this is not recommended unless
you are sure of the cause and the effects of the exception on the
subsystem. In most cases, throwing an EJBException
is preferred.
Exceptions have an impact on transactions and are fundamental to transaction processing. They are examined in greater detail in Chapter 14.