Friday, July 16, 2010

@ApplicationException is evil... sort of

Historically EJB has frowned on RuntimeExceptions. Throwing them results in your transaction getting rolled back and your bean instance being immediately destroyed. You're welcome to try your transaction again ... just as long as you weren't keeping your data in your @Stateful session bean, cause, you know, the container just destroyed that... hope you didn't need it to retry your commit.

In EJB 3.0 the @ApplicationException type was added so that beans could throw RuntimeExceptions and not have their beans destroyed and have the choice to rollback any transaction in progress. Great! Only... how do you really use this for built-in exception types? XML you say? Yuk!


And is the above even a good idea? Definitely not! With something like that you're just asking for trouble. The bad part is that it effectively shuts off transaction exception handling for all beans in the entire application. Currently, though, this is your only option.

The problem is it is hard to use this annotation responsibly. It's often too bold and too difficult to take the hard line that a specific exception type is always fine to throw. It is completely lacking in pragmatism. There is no ability for developers to make a more refined choice.

Bottom line, it should be possible to specify how you would like a RuntimeException handled for a specific bean or method. Imagine @ApplicationException where modified like so:

@java.lang.annotation.Target({TYPE, METHOD})
public static @interface ApplicationException {
    Class value();

    boolean rollback() default false;
Now, we can do things a little more refined:
public static class OrangeBean {

    public void doSomething() {


    public void doSomethingElse() {

In the above, the OrangeBean doSomething method would be allowed to throw a RuntimeException without a transaction rollback or the bean instance being destroyed.

As well, the annotation could be placed on the class level. Say we have an @Stateful bean that wraps an EXTENDED PersistenceContext so that business logic could more easily be done elsewhere, perhaps by an @Stateless bean that uses Bean-Managed Transactions and wishes to batch process several transactions against the EXTENDED persistence context in a loop:

public static class EntityManagerWrapper implements EntityManager {

    @PersistenceContext(type = EXTENDED)
    private EntityManager delegate;

    public void persist(Object o) {

    public  T merge(T t) {
        return delegate.merge(t);

    public void remove(Object o) {

    public  T find(Class tClass, Object o) {
        return delegate.find(tClass, o);

    //... and so on

The EntityManager API does not throw checked exceptions, only derivatives of javax.persistence.PersistenceException which is itself a RuntimeException. To wrap an EntityManager the bean also need the ability to throw javax.persistence.PersistenceException without causing its destruction and transaction rollback. In that vein, the bean is marked @TransactionAttribute(MANDATORY) so it isn't possible to use the bean without already having a transaction in progress, making it clear that transaction management is not it's responsibility.

In another example, say we would like to create a bean that wishes not be destroyed when a RuntimeException is thrown, but it would still like the transactions it starts (via @TransactionAttribute(REQUIRES_NEW)) to be rolled back should a RuntimeException occur.

@ApplicationException(value = RuntimeException.class, rollback = true)
public static class YellowBean {

    public void doSomething() {


    public void doSomethingElse() {


Naturally, to make this API work with more than one exception type per method or bean, we would of course need a new @ApplicationExceptions (note the plural) to group several @ApplicationException annotations -- for those that are not annotation-aware, you cannot use the same annotation twice on a type, method, field or any member.

@java.lang.annotation.Target({TYPE, METHOD})
public static @interface ApplicationExceptions {
    ApplicationException[] value() default {};
With that it would be possible to do all of the above for a few different exception types:
public static class RedBean {

        @ApplicationException(value = RuntimeException.class, rollback = true)
    public void doSomething() {


    public void doSomethingElse() {


In the above the NumberFormatException and ArrayIndexOutOfBoundsException are considered OK and will not cause instance destruction or transaction rollback, however the '@ApplicationException(value = RuntimeException.class, rollback = true)' acts as a default clause of sorts and says all other RuntimeExceptions do not cause instance destruction, but do cause transaction rollback.

Conclusion: Being able to be more specific with @ApplicationException would be a great improvement. I definitely plan to propose it in If you like the idea, please leave a comment as numbers do greatly increase the likelihood of it being added. Other ideas on how to achieve a similar result more then welcome!


Karan Singh Malhi said...

Very nice idea. Definitely a plus if added

bluepluto said...

Having an ApplicationException on the bean side is a good idea, with it, there will be a fine-grained policy for exception handlering. Actually, I just got an issue reported by the customer, they said that the MDB instance is destoryed sometimes, and finally find it is caused by a runtime exception. But from another side, I guess that, for the developers, it might be hard for them to predict which runtime exception will be thrown from the method body, as from the desgin perspective of runtime exception, it is not expected while writing the codes.

aede said...
This comment has been removed by the author.
aede said...

Would definitely be a welcome addition to the specs!

Exception handling is to coarse grained and now the only solution is to use BMT to control the transaction.

Ondrej Medek said...
This comment has been removed by the author.
Ondrej Medek said...


you have a typo in the ejb-jar.xml: java.lang.RuntimeExceptions

should be RuntimeException.

And I have a question. Does it mean, that all subclasses of RuntimeException are considered as ApplicationException, or just RuntimeException itself? Thanks

Ondra Žižka said...

+1. Help me solve:

Marcus said...

I wonder what's the point of throwing an exception and committing the transaction, and why this behavior was chosen for EJBs.

Judging only by the beginning of your post, it looks like you don't like this auto-destruction and auto-rollback behavior (or is it just the auto-destruction that you don't like?).

Would you care to elaborate? If an SQLException escapes my business method, I certainly expect a rollback!

G said...

I would like some finer grained control. Its not clear to me what happens annotation wise if you have a parent EJBException with rollback=false and a child exception with rollback=true. The fate of exceptions that are not caught is also somewhat mysterious. Non-ejb exceptions cause rollback and redirect to error page, ejb exceptions appear to do nothing unless you catch them and handle them manually, which I guess is OK, - they do show up in the log. And why is the default *not* rollback - I could see it both ways, but its strange.

ortigasclover said...

This is really a great read for me. Thank you for publishing articles having a great insight stimulates me to check more often for new write ups. Keep posting!


riveraaissa said...

Nice post.Thank you for taking the time to publish this information very informative! So happy to be given a privilege to post a comment here.


sarah lee said...

I really enjoyed reading your article. I found this as an informative and interesting post, so i think it is very useful and knowledgeable. I would like to thank you for the effort you have made in writing this article.

Leslie Lim said...

I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often..


joy said...

I really had a great time stopping by your site, it gives me a lot of information. You can also visit my site, thank you!

sonu kumar said...

Are you going to end up being shifting to Tucson or by usually there in the 1 1 1 1 1 30 days or so? You can find Tucson movers to help you.
Movers and Packers in Hyderabad
Movers and Packers in Pune
Movers and Packers in Mumbai

sonu kumar said...

Going could be a particularly amazing however nerve-racking party. Having problems in concert along with slugging around those overall look storage space place containers need not end up being one of many problems however.
Movers and Packers in Chennai
Movers and Packers in Bangalore
Movers and Packers in Delhi

Susong Kumar said...

There are actually many different company shifting alternatives that have been available all-time.
Packers and Movers in Noida

Packers and Movers in Navi Mumbai

Packers and Movers in Thane

Packers and Movers in Amritsar

Susong Kumar said...

More so, you should know that if there are many sites, on the internet forums and social media pages, they can be enormously useful. They further reflect more about the opinions of previous customers and users.
Packers and Movers in Jalandhar

Packers and Movers in Ghaziabad

Packers and Movers in Faridabad

Meera Singh said...

Sapphire Packers and Movers in Lucknow

Vishnu Albela said...

Packers and Movers in Pune
Packers and Movers in Bangalore
Packers and Movers Pune
Packers and Movers Bangalore