I am working on EJB 2.1 application .
I have seen a method which is throwing a EJBException (I am working on a enhancement code which is already developed )
Is it neccessary to throw the RuntimeException (EJBException) in this case ??
If it's an exception from which the ejb cannot recover, you should wrap the exception in a RuntimeException (usually an EJBException) and throw it.
With a RT exception (or a system exception) as it is called,
1. Associated transactions are automatically rolled back.
2. The bean is cleaned up (ejbRemove() will be called on the bean).
"Associated transactions are automatically rolled back. "
but are you sure that ejbRemove() will be called on the bean as i read that this method will be get called up when the container decides to remove the bean when it is idle for a long time .
ramprasad madathil wrote:With a RT exception (or a system exception) as it is called,
2. The bean is cleaned up (ejbRemove() will be called on the bean).
The spec just states the opposite:
EJB 3.0 spec section 4.4.3 Missed PreDestroy Calls The Bean Provider cannot assume that the container will always invoke the PreDestroy lifecycle callback interceptor method(s) (or ejbRemove method) for a session bean instance. The following scenarios result in the PreDestroy lifecycle callback interceptor method(s) not being called for an instance:
- A crash of the EJB container
- A system exception thrown from the instance's method to the container
- A timeout [...] while the instance is in the passive state.
You are right about the ejbRemove() and/or the preDestroy() methods.
I do still think that the bean instance will be discarded. Please refer to sections listed in my previous post.
When you use explicitly a EJBException (RuntimeException and "System Exception" in the EJB world) is only for a callback methods and sometimes when you are in a bussiness method and the checked exception is internal and no bussiness.
And raise it is because you realize is a bad idea coontinue with the normal flow therefore is best idea is throws a EJBException
because the Container will do:
1- discard the instance bean
2- log the problem
3. roll back the transaction
But generally when you are in bussiness method and you have a checked exception you should do a call to setRollBackOnly()
and rethrow the checked exception if it is not in the interface method or continue with the bussiness method and check if the transaction
is alive with getRollBackOnly(), maybe it is the main reason to use a EJBException, avoid make extre job.
One more thing, with setRollbackOnly() call you tell to container, the transaction will not commit; remember all this is for CMT.
The exceptions for EJBs is interesting but complicated because there are things for the provider bean and things for the container.
Regards
Aaaaaand ... we're on the march. Stylin. Get with it tiny ad.