EJB 3.0 exceptions handling

MyTitle picture MyTitle · Jan 18, 2013 · Viewed 10.2k times · Source

A quote from the EJB specification:

If the bean method encounters a system exception or error, it should simply propagate the error from the bean method to the container (i.e., the bean method does not have to catch the exception).

But I don't understand it. Does it mean that I shouldn't catch all types of exceptions (i.e. try to catch Exception class) and rethrow it as my application exception?

An example for more clarity:

public void beanMethod throws MyApplicationException {
  try {
    // do something
  } catch (Exception e) {
     throw new MyApplicationException(e); // Should I do it like this? 
  }
}

Or is this not for EJB developers, but only for EJB reference-implementation developers (container developers): In the latter case, as a consequence, the container must not propagate system exceptions to my business method, and my catch(Exception e) block never catches any system exception?

Answer

Donato Szilagyi picture Donato Szilagyi · Jan 18, 2013

There are more type of exceptions:

  • System exceptions (RuntimeExceptions eg. NullPointerException)
  • Business exceptions (your own exception, extends Exception, but not RuntimeException, eg. NotEnoughMoneyOnYourAccountException)
  • Errors (eg. OutOfMemoryError)

Normally you should catch Business Exceptions. But of course you can throw it to the client side if you want to handle it there. By default the EJB container won't rollback your transaction if you throw a BusinessException, but you can change this behavior by annotating your Exception the following way:

@ApplicationException(rollback = true)
public class NotEnoughMoneyOnYourAccountException extends Exception {

If your program throws a RuntimeException, it will be sent to the client wrapped as a RemoteException, and your transaction will be rolled back. These are less excepted than business exceptions, therefore we usually don't catch them at EJB side.

Errors are the least excepted, they can even shut down the JVM, usually we don't catch them, because usually we cannot handle them in the program.