WelcomeTo
WelcomeTo

Reputation: 20591

EJB 3.0 exceptions handling

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?

Upvotes: 13

Views: 11001

Answers (2)

Donato Szilagyi
Donato Szilagyi

Reputation: 4369

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.

Upvotes: 16

Mark Tielemans
Mark Tielemans

Reputation: 1568

I don't know where you got this tip from and what the context is, but it seems to mean that the bean method itself should do no exception handling at all, just throw whatever it gets. That behaviour is usually best realised by adding the Exceptions that your method body may throw depending on environmental/random factors such as variable input in your throws clausule where MyApplicationException is now.

Exceptions that are caused directly by code errors in the method (not in method calls) are usually not required to be properly handled, seen as they should be taken out through testing and debugging.

Upvotes: 0

Related Questions