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?
setRollBackOnly() method. EJB Container does not wrap the exception in case of Application Exception. When System Exception occurs, EJB container intercepts the exception, rollbacks the transaction and start the clean up tasks. It wraps the exception into RemoteException and throws it to the client.
The EJBException is thrown to report that the invoked business method or callback method could not be completed because of an unexpected error (e.g. the instance failed to open a database connection).
Checked Exceptions ejb package (that is, CreateException, DuplicateKeyException, FinderException, ObjectNotFoundException, or RemoveException).
Application exceptions are exceptions related to execution of business logic that the client should handle. For example, an application exception might be raised if the client application passes an invalid argument, such as the wrong credit card number.
There are more type of exceptions:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With