Exceptions and Transactions

Exceptions have a large impact on the outcome of transactions.

System Exceptions Versus Application Exceptions

System exceptions are java.lang.RuntimeException and its subtypes, including EJBException. An application exception is any exception that does not extend java.lang.RuntimeException or java.rmi.RemoteException.

Warning

An application exception must never extend the RuntimeException, the RemoteException, or one of their subtypes.

Transactions are automatically rolled back if a system exception is thrown from an enterprise bean method. Transactions are not automatically rolled back if an application exception is thrown. If you remember these two rules, you will be well prepared to deal with exceptions and transactions in EJB. The bookPassage( ) method illustrates how to use application exceptions:

public TicketDO bookPassage(CreditCardDO card, double price) throws IncompleteConversationalState { if (customer == null || cruise == null || cabin == null) { throw new IncompleteConversationalState( ); } try { ReservationHomeLocal resHome = (ReservationHomeLocal) jndiContext.lookup("java:comp/env/ejb/ReservationHomeLocal"); ReservationLocal reservation = resHome.create(customer, cruise, cabin, price); Object ref = jndiContext.lookup("java:comp/env/ejb/ProcessPaymentHomeRemote"); ProcessPaymentHomeRemote ppHome = (ProcessPaymentHomeRemote) PortableRemoteObject.narrow(ref, ProcessPaymentHomeRemote.class); ProcessPaymentRemote process = ppHome.create( ); ...

Get Enterprise JavaBeans, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.