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.

jessi Amy said...

Marine Muscle is all natural american military grade hardcore legal alternative to steroids. No side effects and no prescription are required.

爸爸 x said...

20170619 junda
oakley sunglasses sale
cheap jerseys wholesale
burberry outlet sale
cheap ray ban sunglasses
adidas uk store
michael kors outlet clearance
cheap nba jerseys
true religion outlet
ray ban sunglasses
nike air max 90

vikas singh said...

summerslam 2017 results
summerslam 2017 live
wwe summerslam live stream

V tight gel said...

provides details about v tight gel which helps in getting tighter vaginal walls and improves ...

Megdalena Blog said...

The 2 Week Diet System developed by Brian Flatt is a fast, effective and healthy weight loss program that assures a fundamental transformation as this method is based on sound biology.

Megdalena Blog said...

The 2 Week Diet System is a unique program that not only assists people to shed those extra pounds but also to spice up their immune system, flatten their tummy and improves their physical power.

Megdalena Blog said...

‘The 2 Week Diet System’ is an impeccable book written by Brian Flatt and Becky Holman, and this book features various physical training systems that will help you to mold your body to the desired shape.

Habib Malik said...

AP SSC Time Table 2018
AP Intermediate Time Table 2018
Goa SSC Date Sheet 2018
Goa Board HSSC Date Sheet 2018

Nicholas Grove said...

sizegenetics We are the only penis enlargement device to show you REAL customer testimonials. Why? Because SizeGenetics™ really works! Learn more.

Phoenix Fun said...

Hi do check out this latest post with our New Blog Post and I hope you would have enjoy all our post
America Got Talent Winner Name Prediction Who Will Win
America Got Talent 2017 Who Will Win
America Got Talent 2017 online voting
America Got Talent 2017 Watch Full Episode
AGT 2017 Winner name Prediction Who Will Win
AGT 2017 who Will Win
AGT 2017 online voting
AGT 2017 Watch Full Episode

Jaipur City Escorts said...

Jaipur Call Girls Service Agency Jaipur City Escorts Provide Best Escorts And Call Girls Servie In Jaipur With All Kinds Female Escorts.

Jaipur Call Girls Service Agency Jaipur City Escorts

Royal Escorts Jaipur said...

Royal Escorts Is A Leading Escorts Agency In Jaipur that Provide The Female Independent Jaipur Escorts Service In Jaipur 24x7.

Female Independent Jaipur Escorts 24x7 Royal Escorts

Royal Escorts Jaipur said...

Call Girls Service Service in mumbai by Ascorts Club.

Ascorts Club Mumbai Call Girls Service

Danish Ahmed said...

Thanks for sharing this article, now you can also check your Admit card & Recuritment 2017 by following below given links...

police si admit card 2017

gpsc medical officer admit card 2017

tamilnadu teacher recuritment 2017

bihar police constable recuritment 2017

gujarat high court recruitment 2017

isiwal technologies said...

I am very happy to see your blog and it is very useful for me and i gathered many information from your blog and thanks for sharing your blog with us ..

Farhan Khan said...

FCI Watchman

Admit Card 2017

CG SET Admit Card


MP Patwari

Admit Card 2017

JEE Main 2018

Application Form

PNRD Assam

REcruitment 2017

Jesica Night said...

Welcome to escorts in Jaipur in our escorts agency collection Indian, Russian and Punjabi model, age lime is 21 to 35. All girl is related to different - different categories like as Air hostess, College girl and business women, Jaipur escorts is very famous for fashionable dream countries.

Jesica Night said...

Jaipur Escorts Service presents the group of Jaipur call girls those are friends and work independently. They are available for an incall facility and outcall as well Jaipur Escort and all around india.

Welcome to escorts in Jaipur in our escorts agency collection Indian, Russian and Punjabi model, age lime is 21 to 35. All girl is related to different - different categories like as Air hostess, College girl and business women, Jaipur escorts is very famous for fashionable dream countries.

other city. We are always delivering satisfying, sensual and erotic escorts services. The top independent Jaipur escorts agency offers dinner and event companions, role play,Call Girls In Jaipur fantasy fulfillment, overnights, bachelor parties and travel With Escorts In Jaipurcompanions.