EJB 3.0 Exception Handling

Quote from the EJB spec:

If the bean method detects a system exception or error, it should just pass the error from the bean method to the container (i.e. the bean method should not catch the exception).

But I don’t get it. Does this mean that I do not have to catch all types of exceptions (i.e., Try to catch the Exception class) and reconstruct it as an exception for my application?

An example for clarity:

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

Or is it not for EJB developers, but only for developers of reference EJB implementations (container developers): In the latter case, as a result, the container should not extend system exceptions to my business method, and my catch(Exception e) block never gets into system exception?

+8
java java-ee exception ejb
source share
2 answers

There are more types of exceptions:

  • System Exceptions (RuntimeExceptions, e.g. NullPointerException)
  • Business exceptions (your own exception, an Exception extension, but not a RuntimeException, such as NotEnoughMoneyOnYourAccountException)
  • Errors (e.g. OutOfMemoryError)

Usually you should catch business exceptions. But, of course, you can throw it to the client side if you want to process it there. By default, an EJB container does not roll back a transaction if you throw a business exception, but you can change this behavior by annotating your exception as follows:

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

If your program throws a RuntimeException, it will be sent to the client terminated as a RemoteException, and your transaction will be canceled. They are less excluded than business exceptions, so we usually don’t catch them on the side of EJB.

Errors are least eliminated, they can even disable the JVM, usually we will not catch them, because usually we cannot process them in the program.

+10
source share

I don’t know where you got this review from and what the context is, but it seems to mean that the bean method itself should not handle exceptions at all, just drop everything it gets. This behavior is usually best implemented by adding exceptions that may be handled by your method body depending on environmental / random factors, such as variable input in your clause throws , where MyApplicationException now.

Exceptions directly caused by code errors in a method (not method calls) are usually not required for proper handling, since they must be removed by testing and debugging.

0
source share

All Articles