I keep getting this "suggestion" from many fellow developers over and over again. In my experience I've found that EJBExceptions are well-suited for "end of the world" from the bean instance perspective (like when something is so wrong that the bean instance cannot recover by itself). If an instance can recover, I think it's better to throw an application exception.
Here is the pattern that I meet over and over again:
private SomeResource resource; ejbCreate: resource = allocateResource(...); omMessage: try { ... } catch (JMSException e) { throw new EJBException(e); } ejbRemove: freeResource(resource);
IMHO this is a antipattern that causes resource leaks.
EDIT: Specifically, the EJB specification says that if a bean throws a runtime exception (and EJBException is a runtime exception) from the business method, then the bean is discarded without calling ejbRemove on it.
Is this a relevant example against throwing an EJBException? What are the relevant cases when EJBException should be thrown?
The throwing of EJBException
is recommended by the EJB spec (14.2.2 in the EJB 3) in the cases where the EJB cannot recover from an exception it encounters. The spec also says that the EJB can reasonably allow (unchecked) System Exceptions to propagate to the container.
I agree with your reading of the spec that in such cases life-cycle callback methods will not be invoked by the container, and hence your concern that any resource-tidy up that would normally happen in the ejbRemove()
callback will not happen and so there's a danger of resource leakage.
My experience is that very many tricky problems arise because of a lack of defensive coding. "Situation X cannot occur in a well behaved system, and if it does then the whole system is broken, so I'll not code for that eventuality." Then we get some "interesting" alignment of the stars and operator errors and the "can't happen" happens several times in quick succession and unanticipated side-effects kick in leading to really difficult to diagnose problems.
Hence I would say:
TransientException
checked exception.ejbRemove
then you can allow SystemExceptions to propogate - but I'm not sure that this is friendly. You depend upon a library and it throws a NullPointerException
. Is is actually more robust to catch and rethrow TransientException
?EJBException
or a system exception so that the instance is destroyed, but at least you've tried to do the housekeeping.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