Ragul
Ragul

Reputation: 335

Can i throw all the exceptions from an EJB as my custom unchecked exception?

As mentioned in this link Why throwing an EJBException is a "recommended" practice?

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.

question1 : what does 'bean will be discarded' means here ?? do we need to lookup again in that case ??

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

Let's consider my ejb method will insert data into 4 tables . If an exception occurs in the code after inserting data in 2 tables, i will not prompt the exception to user for getting a valid data from the user and process it and insert the data in 3rd n 4th table. Instead, i will just ask the user to call the EJB method again with proper data .

question 2 : which of the following 3 is better option

Thanks in advance..

Upvotes: 1

Views: 2053

Answers (1)

Brett Kail
Brett Kail

Reputation: 33936

Question 1 - It depends on the bean type:

  • Stateless - The specific bean instance will be discarded, so subsequent requests will use new instances. Since stateless inherently have no client affinity, there shouldn't be any effect on calling code
  • Stateful/MDB - The bean instance will be discarded, and since instances are 1-to-1 with client references, any data stored in the bean will be lost, and the client would need to start over by creating a new bean.
  • Singleton - The discard is ignored and the same instance is used regardless of unchecked exceptions. Bean providers have to be careful not to allow unchecked exceptions to corrupt the bean state.

Note that when an unchecked exception occurs, the transaction will be marked for rollback only, so any database updates will be discarded.

Question 2 I generally do #2: checked exceptions as custom exceptions and unchecked exceptions as EJBException. You want to use custom exceptions so the calling code can catch and handle them. It doesn't really matter what you use as an unchecked exception since the container will map it to an EJBException for the client anyway, so EJBException is convenient, but there might be some value in a custom exception type for unchecked exceptions for logging purposes.

Upvotes: 2

Related Questions