Discussions

News: Exception management and error tracking in J2EE

  1. Javaworld has an article entitled "Exception management and error tracking in J2EE," which "provides the basis for developing a set of policies along with a supporting framework for error handling in the J2EE world."

    The authors refer to an application-wide user session - a session that can be propagated to different application layers such as web applications, EJBs, EIS modules, and other J2EE components.

    The requirements for handling exceptions, for the authors, are:
    • Use unchecked exceptions: By using checked exceptions, clients are forced to take a position on errors they can rarely handle. Unchecked exceptions leave the client with a choice. When using third-party libraries, you don't control whether exceptions are modeled as checked or unchecked ones. In this case, you need unchecked wrapper exceptions to carry the checked ones. The biggest tradeoff in using only unchecked exceptions is that you can't force clients to handle them anymore. Yet, when declared as part of the interface, they remain a crucial element of the contract and continue to be part of Javadoc documentation.
    • Encapsulate error handling and install a handler on top of each tier: By having a safety net, you can focus on handling only exceptions relevant to business logic. The handler performs the safe touchdown for the remaining exceptions at the specific tier executing standardized steps: logging, system management notification, transformations, etc.
    • Model the exception hierarchy using a "simple living" approach: Don't automatically create new exception classes whenever new error types are discovered. Ask yourself if you are simply dealing with a variation of another type and if the client code is likely to explicitly catch it. Remember that exceptions are objects whose attributes can, at least to some extent, model the variation of different situations. Less than a handful of exception classes will most likely prove enough to satisfy a starting point, and only those that are likely to be handled need specialized attributes.
    • Give meaningful messages to end users: Unhandled exceptions represent unpredictable events and bugs. Tell this to the user and save the details for the technical staff.

    The authors use aspects to add custom exception handling at various levels in the hierarchy, eventually bubbling up to the web layer or to a client layer (ostensibly in Swing or something else.)

    There are a lot of assumptions in the article: an application-wide session, aspects as exception wrappers, and the doctrine of unchecked exceptions, increasingly common among Java developers. It seems like a lot of "cure" for the "disease." Should J2EE address exception handling in such a way to make articles like this less necessary? If so, what would a generic exception handling solution look like?

    How do you handle exceptions in J2EE?

    Threaded Messages (47)

  2. FWIW, the J2EE Web Tier Expert Group members had a meeting at the tail end of JavaOne. One of the primary goals going forward is to have been error reporting - in all the technologies supported by Java EE's Web Tier: JSP, JSF, Servlets.

    It was particularly interesting to see that Tapestry's line-precise error reporting is the model we hope to replicate. Of course, there will be different levels of reporting: one for development and one for production.
  3. This is a very good article that summarizes the issue:

    http://www-128.ibm.com/developerworks/java/library/j-ejbexcept.html

    Regards,
    Emil (http://testare.dev.java.net)
  4. This is a very good article that summarizes the issue:http://www-128.ibm.com/developerworks/java/library/j-ejbexcept.htmlRegards,Emil (http://testare.dev.java.net)

    I wrote that article for IBM developerWorks more than three years ago.
    The newer version of that exception handling best practices article specifically applied to web applications can be found in a book that I wrote some time back. The ebook is available free here: http://www.objectsource.com/Struts_Survival_Guide.pdf

    Look at Chapter 9.

    Cheers,
    Srikanth
  5. The most complete I've found:

    http://www.blueskyline.com/ErrorPatterns/A2-LongshawWoods6.pdf

    Cheers,
    Omar
  6. Patterns on exception managment[ Go to top ]

    http://www.blueskyline.com/ErrorPatterns/A2-LongshawWoods6.pdf

    Great! Thank you!
  7. Some background:

    I use STRUTS/Tomcat.

    I use a rather mature DAO framework that I started back in the late 90's. I've elected not to use a third party O/R mapper after experience with TopLink, OC4J, Cocobase, Versant, and Castor - all of which simply pushed complex persistence reasoning tasks to the metadata, a 'lipstick on a pig' approach to solving the impedance mismatch problem.

    My exception handling philosophy is to catch all exceptions in one layer. I've chosen to catch all relevant exception types in the Struts Actions, since that is where a decision is made about where to send a user after processing (if an exception is recoverable, then the user can be sent to a recovery page, otherwise send them to a nice error page).

    I catch unchecked exceptions in the Action classes in the last catch block of my Action execution. I catch checked exceptions explicitly if there is a way to recover (invalid user input, z.b.).

    I throw all checked exceptions from my DAO classes and utility classes, defining them in the method signatures. I do not require that unchecked exceptions be thrown explicitly.

    I log any exception that occurs in the system at the Action level, and use log4j metadata to control which exceptions are logged - by level and by class.

    This is what has worked for me in building STRUTS apps over the last 7 years.
  8. This is what has worked for me in building STRUTS apps over the last 7 years.

    And what about this - Struts At Five Years ? :)
  9. This is what has worked for me in building STRUTS apps over the last 7 years.
    And what about this - Struts At Five Years ? :)

    Reminds me of a guy who was arguing with me recently about using taglibs vs. Java code in JSPs. Since he had no technical backing to his argument, he said he knew this because he had 10 years of Java web app experience on 2 continents... I stopped the argument there.
  10. Why?[ Go to top ]

    ...when there are sometimes situations that call for using java code in JSP's.

    So I sacrificed some credibility by not proof reading a post, and you ignore people who disagree with you about a dogmatic approach to some technology decisions, i.e., struts tags and O/R mapping.

    Let's move on, shall we?

    Care to offer your opinions on why <insert contemporary metadata based O/R mapper implementation here> will succeed and the one's I mentioned have yet to dominate the O/R space or, in some cases, even continue breathing?

    And what are your thoughts about my approach to exception handling? I am always interested in improving upon my development approaches.

    Why are you a credible source/authority for these topics?

    Best.
  11. Why?[ Go to top ]

    I actually use the exceptions based on the article Make Exceptions Smarter. In essence, a hierarchy of property files hold strings that map to very detailed exception messages.

    I use these in conjunction with most unchecked exceptions. After reading the Bruce Eckel article, I decided that his premise was sound and it was worth testing.

    I believe that my code is much cleaner when using unchecked and certainly much more descriptive.
  12. My Brand of Exception Handling...[ Go to top ]

    Reminds me of a guy who was arguing with me recently about using taglibs vs. Java code in JSPs. Since he had no technical backing to his argument, he said he knew this because he had 10 years of Java web app experience on 2 continents... I stopped the argument there.

    Hah! Don't know your argument but you were wrong to stop it. Java was out 1995 and I was actually coding my first experimental cgi script with it in 1996. And I was not the first one. Let alone applets.

    The doom of man is that they forget :-)
  13. and my appologies for the oversight.

    Servlets since 1998, J2EE since 2000, and Struts since 2001.

    In 2000 my company was using BEA's EBCC, before I had any exposure to STRUTS.

    Best Wishes.
  14. and my appologies for the oversight.Servlets since 1998, J2EE since 2000, and Struts since 2001.In 2000 my company was using BEA's EBCC, before I had any exposure to STRUTS.Best Wishes.

    One could argue BEA Webflows are pretty much what Struts provided anyway. Though in 1999 they used property files instead of XML. Doesn't really matter, both are a pain to edit :-)
  15. My Brand of Exception Handling...[ Go to top ]

    Some background:I use STRUTS/Tomcat.I use a rather mature DAO framework that I started back in the late 90's. I've elected not to use a third party O/R mapper after experience with TopLink, OC4J, Cocobase, Versant, and Castor - all of which simply pushed complex persistence reasoning tasks to the metadata, a 'lipstick on a pig' approach to solving the impedance mismatch problem.My exception handling philosophy is to catch all exceptions in one layer. I've chosen to catch all relevant exception types in the Struts Actions, since that is where a decision is made about where to send a user after processing (if an exception is recoverable, then the user can be sent to a recovery page, otherwise send them to a nice error page).I catch unchecked exceptions in the Action classes in the last catch block of my Action execution. I catch checked exceptions explicitly if there is a way to recover (invalid user input, z.b.).I throw all checked exceptions from my DAO classes and utility classes, defining them in the method signatures. I do not require that unchecked exceptions be thrown explicitly.I log any exception that occurs in the system at the Action level, and use log4j metadata to control which exceptions are logged - by level and by class.This is what has worked for me in building STRUTS apps over the last 7 years.
    What do you do with your exceptions in business objects ? do they comeback to actions too ?
  16. What is a business object?[ Go to top ]

    Is it an EEJB? Is it a stateless/stateful Session Bean? Is it a simple Java wrapper that facilitates a centralized, consistent nomenclature only?

    If you can be a little more specific, then I will have a better shot at addressing your question - context is everthing.

    The systems that I have been building recently do not propagate exceptions past a network boundry, because clients are HTML based - READ: ALL HTTP BASED COMMUNICATION ACROSS NETWORK BOUNDRIES.

    If I were writing Remoted Thick Java Clients, I would likely take the same strategy, then rethrow new checked exceptions to prevent security vulnerabilities. I would throw a custom exception type to handle any unchecked server-side exceptions to indicate a critical system failure to the clients (not that any such condition would occur in my software ;) .
  17. In my highest Struts base class, I turn all exceptions(overwhelmingly runtime) into Struts ActionErrors and display them as a bulleted list. I never really cared for the shunting to error pages.
  18. In my opinion, having a generic generic exception handling framework is a design smell... And I think it was largely led to it by preferring runtime exceptions over checked ones. It is funny that author begins by:
    Use unchecked exception.
    and ends with:
    Unhandled exceptions represent unpredictable events and bugs.

    Completely ignoring the fact that the only guaranteed way to get unhandled exceptions (and thus "unpredictable events and bugs") in Java... is to use runtime exceptions!

    Nikita.
    GridGain Systems.
  19. Completely ignoring the fact that the only guaranteed way to get unhandled exceptions (and thus "unpredictable events and bugs") in Java... is to use runtime exceptions!Nikita.GridGain Systems.

    This statement only proves to me that the introduction of checked exceptions in Java has had more negative consequences than any benefits checked exceptions were supposed to provide! Somehow, so many developers now assume that the only exceptions that should be handled are the ones the compiler reminds them of! Are you serious? If you rely on the compiler when implementing error handling, you are doing something really wrong. Your application should ALWAYS catch ALL errors, and you should always remember that - regardless of what the compiler tells you. The existence of "checked" exceptions is misleading, gives too many programmers a false sense of security: if there are no more checked exceptions to catch, my error-handling is taken care of. Now, that's the "only guaranteed way to get unhandled exceptions", Nikita. Not to mention the fact that most checked exceptions are never really handled by the clients b/c the clients don't know or don't care what to do with them. Useless checked exceptions pollute the code, _provoke_ developers to either swallow/ignore errors (when they don't know what to do with them and the compiler demands that the exception is caught) or to re-throw them left and right, and handle errors inconsistently. I don't know of any other area of J2EE development that is so convoluted and misused as exception handling - from project to project - thanks to checked exceptions. Ah well... don't want to get into the never-ending debate... It's good to see that more and more people are finally moving in the right direction.

    Speaking of the article, I think it's brilliant! After much debate, we have just implemented practically the same approach to refactor error handling in our project: using RT exceptions for all _unrecoverable_ conditions, AOP, ThreadLocal, etc. Solved a lot of problems!
  20. Kind advice: if you want anybody taking you seriously, start off by putting your real name where your mouth is...

    Nikita.
    GridGain Systems.
  21. +1[ Go to top ]

    Kind advice: if you want anybody taking you seriously, start off by putting your real name where your mouth is...Nikita.GridGain Systems.

    anonymity rears its ugly head.
  22. Kind advice: if you want anybody taking you seriously, start off by putting your real name where your mouth is...Nikita.GridGain Systems.

    Sorryy... Thanks for the advice. Very kind, indeed. I actually realized that I had some silly alias from a long time ago displayed - after I posted my note, and I changed that immediately, even before you posted your smartass response. I don't think I have anything to hide. :)

    Oh... but you still don't have to take me seriously... ;)
  23. (off topic)[ Go to top ]

    Constantine,
    Your name was like “crazy glue” or something. So, i thought I'd point it out that it better put a real name in a serious conversation. Sorry, for jumping a gun.

    As far as exception handling... I believe you are seriously misguided but that's my opinion.

    I can probably take a higher ground and say that I have a fairly unique experience of running a complex and large middleware project on both Java and .NET (C#). We took issue w/error handling almost on academic level (with our own profiling/analyzing tools using AspectJ almost 3 years ago, building checked exception support for .NET MSIL, etc.). So, my albait short comments are actually backed up by substation expertise in this area.

    As far as “other” project and people using RT exception – some of that can be easily explained: TopLink was migrated from Smalltalk that just did not have the concept of checked exceptions (it was pioneered like a decade later in general use), JDO/Hibernate can't use checked exceptions for some good design reasons (code augmentation being the obvious one), Python is a light-weight scripting language, etc.

    Spring is the only one in your list that made this choice (and I believe wrongly having used Spring in couple projects now).

    Regards,
    Nikita.
    GridGain Systems
  24. (off topic)[ Go to top ]

    Nikita,

    I applaud you for having the vision 3 years ago to realize the power and potential of Aspects, as well as the dedication to make good use of them in your project. I have just recently started using AOP, and believe it adds incredible value and power, if - as with anything - used properly. I am sure you have met or heard from many people in the past years who had told you that AOP was evil. I read such opinions on the net almost every day. Most objections come from people who haven't taken time to actually study the subject, who haven't put a lot of thought and effort into an actual design and tried it out. Such people just read a headline and feel they have to stick their opinion (often, quite insulting) in the face of some guy who has done a successful AOP project and simply tries to share the experience. As someone who obviously have experienced the value of aspects, you know that such uneducated arguments and remarks are undeserved. That's why I am surprised to read this:
    As far as exception handling... I believe you are seriously misguided but that's my opinion.

    Sound a bit patronizing, doesn't it Ok, I won't hold it against you. Let's just say, you disagree. And I can see exactly why:
    I can probably take a higher ground and say that I have a fairly unique experience of running a complex and large middleware project on both Java and .NET (C#). We took issue w/error handling almost on academic level (with our own profiling/analyzing tools using AspectJ almost 3 years ago, building checked exception support for .NET MSIL, etc.).

    So, you have spent 3 years _running_ (not just participating in) a project that included adding checked exceptions to C#, which I am sure took a lot of development hours, and your company has spent a dime or two on that... Now, whould you be willing to embrace the idea that all error handling issues you have been addressing with such effort and dedication could have been taken care of with much less time and effort? What are the chances that you opinion may be a tiny bit biast? ;)

    True, I haven't spent any time on adding the support for checked exception to any language that purpously has avoided it. Instead, I have spent at least 10 years developing critical applications in C++ (among other languages) - prior to getting into Java. That's how I first got introduced to the concept of exceptions. See, the designers of C++ introduced the concept of exceptions and TRY/CATCH blocks to simplify error handling and ensure that error handling could be consolidated in a proper place in the calling chain - instead of being sprinkled all over the place. The approach allows the methods that have no ability to do anything about the error to be completely free of error handling code. Instead, you place the error handling code where it belongs, in the method that actually knows how to handle the error and how to proceed. All C++ exceptions were made unchecked, an NO ONE HAD EVER SAID that the unchecked exceptions should not or might not be caught! You must catch everything, but it depends on the application design where to place the error handling code. Note: no code pollution in the methods along the call chain between the error source and the method that actually handles the error! Java came around with this seemingly great concept: let's help people remember that they must catch errors. The checked exceptions brought back the necessity for all the methods on the call chain to be aware of any checked exception that may be thrown down below - even if they can't do anything about it. In addition to unnecessarily exposing all such methods to the implementation details of some other methods down below, that has caused a lot of general confusion and resulted in the fact that there are very few Java developers (a tiny per cent, I am convinced) who actually know how to properly handle exceptions. That's why it is still such a big issue throughout the Java community. Like the authors of the article in question, I have used checked exceptions for years trying to find the best way, doing my own research and learning from some great co-workers, as well as listening to the opinions different from my own. Only after that, have I come to the conclusion: Java's checked exceptions add more trouble than value, and there is a good, simple and inexpensive way to handle errors. The essense of the approach is presented in the article. If you invest a few minutes in reading it with an open mind, I am sure you will see that it does indeed solve the problem (and the design does not "smell" at all):

    1. Nothing prevents you from using checked exceptions, you are encouraged to use them only when they are appropriate - when the application can actually be expected to take an alternative business action in responce to the error (not just logging and reporting an error.)
    2. ALL errors get properly caught, thanks to the safety nets on the boundary of each tier, and other design solutions.
    2. The error info gets propely logged, with all necessary context information.
    3. The code becomes cleaner; much less code needs to be written.
    4. The maintenance becomes easier.
    etc.

    It does work! I know it because we have done the same thing just weeks ago. I find it unfair that so many people in this forum dismiss someone's excellent and hard work after having read only a short abstract of the article... The only fair way to argue is if one knows and fully understands the other party's point of view. I have been on both sides of the fence, and I have found out for myself what's right. I guess that puts me in the same boat with such "seriously misguided" people as Bruce Eckel (http://www.mindview.net/Etc/Discussions/CheckedExceptions) - the author of Thinking in Java, Anders Hejlsberg - the chief architect of C# (http://www.artima.com/intv/handcuffs.html), Rod Johnson (Spring, )and many others.

    Cheers,
    C
  25. Off topics[ Go to top ]

    Kind advice: if you want anybody taking you seriously, start off by putting your real name where your mouth is...Nikita.GridGain Systems.

    How do I know Nikita is your real name? Maybe you should also post your creditcard number, expiration date and the three-digit verification codes, if I can charge it, it is PROBABLY a real name (though I'm still short of proving that's you who's writing.)

    This is the Net. Too many risks!
  26. totally agree with this[ Go to top ]

    I know from experience that good exception handling and logging helps analyze problems with remote servers. I've found myself analyzing problems on remote servers running our software more than once with my hands tied behind my back (think the sysadmin grudgingly mailing me fragments of the tomcat log if I begged hard enough). At times like this you can really benefit from proper exception handling: the log tells you what happened and where and why.

    Besides, IDEs like eclipse make it very easy to catch exceptions. It would be pure lazyness not to use them. You shouldn't overuse them of course. It's sometimes tempting to use them for conditional logic but you shouldn't do that imho.

    Often in J2EE environments you work with stuff that can fail for all sorts of reasons. For example your database connection pool may run out of connections because the driver you use has a bug, a sysadmin may inadvertedly shutdown a webservice, an overzealously configured mailserver may reject your javax.mail composed messages, etc. You need to be able to recover from this sort of things because they can and will happen.
  27. totally agree with this[ Go to top ]

    Besides, IDEs like eclipse make it very easy to catch exceptions. It would be pure lazyness not to use them. You shouldn't overuse them of course. It's sometimes tempting to use them for conditional logic but you shouldn't do that imho.Often in J2EE environments you work with stuff that can fail for all sorts of reasons. For example your database connection pool may run out of connections because the driver you use has a bug, a sysadmin may inadvertedly shutdown a webservice, an overzealously configured mailserver may reject your javax.mail composed messages, etc. You need to be able to recover from this sort of things because they can and will happen.

    Again, you guys seems to think - or sound as if you think - that "checked" exceptions are the only exceptions that are caught and handled. That is a totally wrong premise, although, I agree that RT exceptions do get overlooked by developers often. But that's the developer's fault, and the presense of checked exceptions doesn't really save the situation.

    1. The fact that the IDE forces you to handle or re-throw the checked exception before you have compiled your code is certainly very convenient. It is still up to you to _handle_ your errors PROPERLY. Practically on every project I have seen so far, developers would tend to treat exceptions as an afterthought, which eventually would lead to major problems and confusion. For example, the same exception gets caught, logged and re-thrown many times, which results in bloated and confusing log files. Or, an interface defines methods that throw generic (therefore, useless) checked exceptions - because there is no way of knowing what specific exceptions will be thrown by the implementations. The implementations throw specific checked exceptions that immediately get abstracted by the generic super-class. If you are lucky, your client doesn't care to distinguish the specific types and handles all caught checked exceptions the same way. (Then, why do you need those exceptions to be "checked"? Just so that the compiler tells you that SOMETHING may go wrong during the call to the given service? D'uh! Shouldn't you assume that in the first place and catch all errors, not just the checked ones - wherever it is most appropriate per your design - instead of unnecessarily polluting the code and method signatures all along the call chain?) If, in fact, the client is designed to take an alternative course of action depending on the type of the error, then, by all means, the specific checked exception may be useful. But if the client receives a _generic_ checked exception (superclass) that abstracts all sorts of more specific exceptions, you are forced to implement some stupid mickey-mouse logic on the client that would check for "instanceof", or, even worse, some "exception type" attribute on that exception class that will tell you what kind of exception you are dealing with. That completely defeats the purpose of checked exceptions because, at this point, it is you, not the compiler, who does the checking... very awkwardly and unreliably. I'm sure we all have seen this, it's a very common way to handle checked exceptions, unfortunately, and even experienced programmers sometimes do that.

    2. I agree that the term "framework" doesn't very well apply to exception handling. It is more of a combination of good design, best practices, and some framework elements like certain base exception classes, well-implemented logger, etc. This is actually what the article is about. I know many people are afraid to use AOP, but I have found Aspects very useful for harnessing exception handling and logging. We are using AspectJ - very carefully - for example, to enforce and consolidate certain safety nets for error handling, properly reset the session context, unwrap the original RT exceptions from RemoteExceptions in the Spring proxy before propagating the original RT exception to the client, etc. Thanks to Aspects, such things are localized, the code never has to be duplicated, and most developers don't even have to ever worry about them.(I must admit, the trade-off for me was that I had to give up my favorite IDE - IntelliJ - in favor of Eclipse b/c IntelliJ does not support AspectJ the way Eclipse does.)

    3. I'll say it again: all errors must be handled, and nothing in the programming language should mislead the developer. It's an unfortunate fact that Java developers often rely on the compiler to tell them where they have to catch an exception and which one to catch - and therefore disregard the REAL error handling alltogether. This is so common that Nikita states - without a shred of a doubt - that RT exceptions are certain to slip through the cracks and cause your app to blow... And he is correct, unless the developer approaches error handling as a critical part of the application design, not an afterthought. Other languages do not have checked exceptions, and I have not heard of any language since Java that actually went to implement checked exceptions. C# supposedly was developed to take the best from C++ and Java. Well, they passed on checked exceptions... Same with SmallTalk, Python, etc. Spring, Toplink, Hybernate, etc. - none of them uses checked exceptins...

    4. Any environment/system errors are truly unrecoverable errors - in the sense that your application cannot fix them. The application should, of course, gracefully react to them instead of blowing up in the user's face, but it will likely have to handle all such errors in the same generic way. If that's the case, the application will have no use of knowing what particular kind of SQL error has actually occured, or whether the file IO error happened. The error/context info plus the full stack trace should be logged for the administrator/developers to look at, and the user should be presented with a polite message. Therefore, it will only make sense to make such exceptions run-time and, indeed, CATCH and handle all of them where it is most appropriate according to the application design. True, such conditions may be presented as checked exceptions on a deeper level, where the service might want to re-try the operation several times based on the given exception. After all attempts fail, the service should still throw a RT exception to its caller.

    That said, I must admit that I have used checked exceptions for years myself, trying to figure out how to solve the "problems with exception handling" that every project manager I've known complained about. I am totally convinced today that, generally, Java checked exceptions bring very little value while provoking countless problems and unnecessary code complexity.
  28. Not quite[ Go to top ]

    D'uh! Shouldn't you assume that in the first place and catch all errors, not just the checked ones - wherever it is most appropriate per your design - instead of unnecessarily polluting the code and method signatures all along the call chain?)

    The caller should not and cannot handle all kinds of exceptions. For example, if you get NullPointerException's and they are verywhere, you cannot do much about them but to let the upper level (such the main loop or the JVM) to either log-and-ignore or quit altogether.

    But some other errors, from the perspective of the method, the caller may be able to do something. Like if I cannot open a file, maybe I can change to create it.
    Other languages do not have checked exceptions, and I have not heard of any language since Java that actually went to implement checked exceptions. C# supposedly was developed to take the best from C++ and Java. Well, they passed on checked exceptions... Same with SmallTalk, Python, etc. Spring, Toplink, Hybernate, etc. - none of them uses checked exceptins...

    A key purpose of languages, especially strong typed languages like Java, and their compilers, is to help human being avoid errors. Checked exception is a strong-type approach to handle errors.

    The fact is if programmers do not know how to declare and catch exception, they would even less likely to be able to write logic codes to deal with unchecked exception either (or they are just too lazy to do so.) I saw too many codes that programmers just write "throw new RuntimeException("misleading messages like this strange bad thing has occured")" and "catch (Throwable e) log.error(e)"
  29. 1. Or, an interface defines methods that throw generic (therefore, useless) checked exceptions - because there is no way of knowing what specific exceptions will be thrown by the implementations. The implementations throw specific checked exceptions that immediately get abstracted by the generic super-class. If you are lucky, your client doesn't care to distinguish the specific types and handles all caught checked exceptions the same way.

    Java up through 1.3 had a problem with exception chaining -- it just wasn't part of the libraries. This is the problem that exception chaining is designed to address. I find the following idiom useful and correct:

    interface IFoo {
      void method() throws GenericException;
    }

    exception GenericException extends Exception {
      GenericException(Throwable cause) {
        super(cause);
      }
    }

    class FooImpl implements IFoo {
      void method() throws GenericException {
        try {
          ...
        } catch (SpecificException e) {
          throw new GenericException(e);
        }
      }
    }


    Now, the user of IFace need only deal with GenericException if/as necessary. If necessary, the root cause exception is available via GenericException.getCause().
  30. Nothing is achieved.[ Go to top ]

    I dont see the value of going with Genreric Exception approach except it is a code mess.
  31. Nothing is achieved.[ Go to top ]

    I dont see the value of going with Genreric Exception approach except it is a code mess.

    Exactly. And the exception CHECKING becomes virtually disabled! Now you have to catch some meaningless generic exception, manually exctract the original exception, and then what? Use "instanceof" to check the type? And if someone else has written the code that throws that generic exception, how do you know what type to check against? Do you have to dig through thopusands of lines of someone's code to find out this each time? So, how did the compiler help you with that? That's a perfect example of how checked exceptions are being misused. Checked exceptions literally provoke people to write bad code - serving the purpose just the opposite to what the intent of the original Java designers was.
  32. I dont see the value of going with Genreric Exception approach except it is a code mess.
    Exactly. And the exception CHECKING becomes virtually disabled! Now you have to catch some meaningless generic exception, manually exctract the original exception, and then what? Use "instanceof" to check the type? And if someone else has written the code that throws that generic exception, how do you know what type to check against? Do you have to dig through thopusands of lines of someone's code to find out this each time? So, how did the compiler help you with that? That's a perfect example of how checked exceptions are being misused. Checked exceptions literally provoke people to write bad code - serving the purpose just the opposite to what the intent of the original Java designers was.

    The whole thing about use of polymorphism is to make the user of the class implementation agnostic. It is achieved with GenericException which can be for example NotEnoguhPrivilagesException or NoSuchUserException. It is better to have these exceptions checked and force the client code to deal with them as the client code CAN REALLY DO SOMETHING about them (like in this simply display a relevan and meaningful message to the client).

    There's no purpose of checking the instance of or checking against subclass exceptions because that makes the client implementation aware of the implementing classes so where's use of polympohism in this place?

    My oppinion is that fatal exceptions that client cannot deal with should be for sure unchecked while other exceptions which client can (and should) do sth with SHOULD BE definitelly checked. For this reason FileNotFoundException is a checked exception and than if it occurs in the server code and programmer decides it shouldn't happen it should be converted to unchecked fatal exception and rethrown to higher layers.
  33. Server side has no rights to force any type of exception handling to client.

    There will be clients which care and clients which dont care about our server side exceptions. So leave them decide what to handle and what not.

    With checked exceptions you force all clients to handle your exceptions some how.
  34. There's no purpose of checking the instance of or checking against subclass exceptions because that makes the client implementation aware of the implementing classes so where's use of polympohism in this place?

    Exactly! Then what do you need a checked exception for in this case? The code in your method throws SomeException that extends your GenericException, but the method's signature defines GenericException. Immediately, you hide your actual exception under that GenericException. Instead, your GenericException tells the caller that SOMETHING may not work inside the called method (who would have thought?!), so go ahead and catch it. Well, what if the caller doesn't care b/c it can't do anything about it? If there is someone else in the call chain who can and should catch an error - per design - it must catch that error, otherwise the method is flawed. (Don't even start! I know what you are going to say. :) No compiler can advise you _how_ to properly design and implement your code. All it can tell you is that this particular exception must be caught AT SOME POINT; it's up to the developer to decide WHERE and HOW. Many Java developers rush to handle checked exceptions as soon as they see that the compilers complains, often without much thought: just to make it compile and move on! It's a fact. And Java literally encourages such mistakes.) So, your GenericException might as well be a runtime exception. You are not adding any value by forcing all methods in the call chain to provide code just to propagate that GENERIC exception to the actual handler. And by the way, this is not what polymorphism is about...
  35. totally agree with this[ Go to top ]

    For example your database connection pool may run out of connections because the driver you use has a bug, a sysadmin may inadvertedly shutdown a webservice, an overzealously configured mailserver may reject your javax.mail composed messages, etc. You need to be able to recover from this sort of things because they can and will happen.
    How do you handle this kind of problems in code ? Do you fix driver bug in exeption handler and continue to serve clients ? I think it better to let crash than to handle drivers bugs or misconfiguration (no result is better than wrong result)
  36. totally agree with this[ Go to top ]

    For example your database connection pool may run out of connections because the driver you use has a bug, a sysadmin may inadvertedly shutdown a webservice, an overzealously configured mailserver may reject your javax.mail composed messages, etc. You need to be able to recover from this sort of things because they can and will happen.
    How do you handle this kind of problems in code ? Do you fix driver bug in exeption handler and continue to serve clients ? I think it better to let crash than to handle drivers bugs or misconfiguration (no result is better than wrong result)

    It's never good to let the application crash (what if your app runs a critical process on a space shuttle?) However, such errors - the ones that your application has no way of fixing should be cought by a safety net (which is a must!), and such errors must be represented by runtime exceptions so that your code is not polluted with useless try/catch blocks and throws clauses. Again, I agree with you that it should be a RT exception, but, like so many people, you seem to assume that RT exceptions fall through and are never caught. That's wrong. The exceptions (unchecked!) in C++ were introduced NOT to be ignored, but to be handled in convinient - appropriate by the design - places instead of having each method on the call chain to worry about error handling even if the particular method can't and shouldn't do anything about the error.
  37. Nothing good.[ Go to top ]

    Lets put this way Checked Exception offer no benefits of Runtime Exceptions except have compiler complain that code doesnt handle it.

    The point is that this benefit does more harm than use by forsing me to re declare the exception in call chain in 80% of time.
  38. totally agree with this[ Go to top ]

    It's never good to let the application crash (what if your app runs a critical process on a space shuttle?) However, such errors - the ones that your application has no way of fixing should be cought by a safety net (which is a must!), and such errors must be represented by runtime exceptions so that your code is not polluted with useless try/catch blocks and throws clauses.

    "Unknown" exception means bug in code,wrong configuration or some stuff I can not control. Handler can not fix unknown error, but it can produce side effect (like driver bug hunting ). There are better ways to handle errors outside code (like driver upgrade).
    There are many ways to "crash" too. If you abort transaction and send user to error page then it is a "crash" too, is not it ? It just informs user or administrator about "crash", it doe's not fix the problem.
     Probably it is the mater of taste, but I prefer to test precondition using "if" statement, it is hard to understand control flow implemented using exceptions, stuff like resource cleanup must be implemented in "finally" block anyway. I found exceptions are usefull for error diagnostic only, checked exceptions do not help to diagnose error too.
  39. +1 ... although you can't rely on all exceptions being RT exceptions.

    I found this pretty darn confusing:
    "Yet, when declared as part of the interface, they remain a crucial element of the contract and continue to be part of Javadoc documentation"

    Since when is Javadoc==interface? Good luck if you follow this practice.
  40. +1 ... although you can't rely on all exceptions being RT exceptions.I found this pretty darn confusing:
    "Yet, when declared as part of the interface, they remain a crucial element of the contract and continue to be part of Javadoc documentation"
    Since when is Javadoc==interface? Good luck if you follow this practice.

    Nothing prevents you from specifying a runtime exception in the Throw clause. If you do, the exception will be reflected in the Javadoc as well.

    BTW, we have implemented almost the same approach just a few weeks ago, and it indeed works beautifully. The code is much, much cleaner, the logs are clear and informative, and maintenance becomes much less of a headache... But, hey, no one says it's the only way. :)
  41. Yet, when declared as part of the interface, they remain a crucial element of the contract and continue to be part of Javadoc documentation.

    That sounds like a good idea, but how to enforce the throws clauses of the interface methods to stay correct when the implementation is changed and new exceptions are potentially thrown or old ones no longer? Sounds like a manual, error-prone, task selecting which unchecked exceptions should be declared.
  42. If it is becomes "manual, error-prone" than the contract of the interface was not done properly.

    Personally I have been advocating use of unchecked exceptions for a long time especially no exception declaration in interfaces because EXCEPTION IS IMPLEMENTATION CONTRACT AND NOT TYPE OR OPERATION.

    Anyways there are no generic Exception handling best practices it all depends on situation, even JEE is big enough not to have one Exception management solution.
  43. deprecate the old method signature and add another method with the new exceptions. A drawback is that this will require renaming the method unless some parameters have also changed since the last release. The upshot is that you won't break the 10's ( ;o) ) of thousands of clients that depend upon your software. If you have made some critical adjustment to system structure that requires a new method - usually a result of a non-maintainable design - then you force your clients to rewrite their code, and make sure the required update path is avidly communicated to...your 10's of thousands of clients.
  44. Exception Manangement[ Go to top ]

    Divide your exceptions into four categories:
    1. Exceptions the application should resolve - such as a stale database connection or a broken network connection
    2. Exceptions the user can resolve - such as an exception due to invalid input
    3. Exceptions requiring an administrator to resolve - such as a database being offline
    4. Exceptions due to software bugs - such as a NullPointerException

    I think exceptions in categories 1 and 2 should be checked and handled in the application close to where they occur. 3 and 4 should be unchecked and handled by a generic error handling and reporting layer.

    The problem is some exceptions (like an SQLException) may fall into any one of those four categories. The category an exception falls into may be dependent on the expected reliability of the application.
  45. I have seen people advocating use of Checked Exception - even to the extent that RuntimeExceptions should be converted into Checked ones. Argument - SQLException is Checked.
  46. I'd like to clarify some points here. Based on my experience my primary concern not with RT exceptions specifically but with approaches that advocate almost ***exclusive*** use of RT exceptions.

    Both RT and checked exceptions obviously have their uses. I believe the JDK is well designed in this sense and amount of RT and checked exceptions is somewhat balanced. When I interview engineers I often ask to name me any exception in standard JDK that they would switch from RT to checked or vice versa. Very rarely anybody comes up with something they can vaguely back up.

    I think in general the people that share my view usually argue against blanket usage of RT-only exceptions. I just looked back at my sources and seems like out of all exceptions I have created lately – only 10-15% were RT. Obviously, these numbers mean nothing in a larger context but they just show the relative place of RT exception in a generic server side code in my view.

    Regards,
    Nikita.
  47. Thou shall know the application[ Go to top ]

    Nikita, the design chioce for your application maybe perfectly right coz it's a middleware application (if I'm assuming correctly). The whole argument FOR checked exceptions are that they make it easy for users to take actions on it. In your case you can't assume who will use your app/component/framework and hence be explicit about errors.

    This same strategy would be naive in most biz apps where biz logic errors maybe/shudbe modeled as checked, while rest are all unchecked.
  48. My five cents[ Go to top ]

    I am the co-author of the article that fueled the heated debate in this thread. Much has already been said, and thanks to Constantine there is little I have to add at this point. Instead, let me provide some background info.

    The rules and framework elements that are presented in the article are in use today within healthcare and are the result of experiences harvested from many a Java project. They are being applied in a virtual development organisation composed of engineers at different locations and from different companies working in teams on business components and applications.

    One team develops a component that deals with information about patients; another with a component for handling staff and organisational relations. The components are used by larger applications e.g. for controlling medication of all patients in a region or for handling daily medical procedures on patients. A central architecture team is responsible for providing guidelines, frameworks, and for ensuring consistency across teams and projects. This is what we do.

    Exception handling can be tough enough to get under control in a single project with a few engineers, but obviously our environment is much more challenging. In response to this challenge we started out by examining worst-practices and short-listed a set of rules e.g. "Never catch the generic Exception" (because you are also catching RTs) and "never swallow an exception" (because often times that will cause something else to break down the line and make it VERY hard to pinpoint the actual cause).

    Rules are great, but they have to be easy to follow and implement, and if possible, enforced. This is where the framework fragments come in:

    A base exception hierarchy makes for reuse of existing errors, makes it easy to track exceptions pertaining to your applications, and provides a base for common attributes (e.g. error codes).

    The last line of defense should always be there for those stray NullPointerExceptions, ArrayIndexOutOfBoundsExceptions, and the like regardless of whether you do your exceptions RT style or prefer them checked. This is the job of the top-level exception handlers.

    By chosing to base the hierarchy on RTs, we make the code much more readable by avoiding the Catch, Wrap, Throw idiom and some of the rules e.g. the ones from before "don't catch Exception", "Don't swallow exceptions" are automatically followed b/c developers aren't forced to catch what they can't deal with anyway.

    True, we loose a compile-time check, which imho is flawed in the first place: There may be a few cases where a service can anticipate what error situations a client can deal with, but in my experience this is rarely the case. I guess this is where the debate tends to get slightly religious :-).

    In any case, the effects of enforcing our rules and frameworks are that exception handling is now being implemented in a coherent fashion across components and applications. This makes it much more likely that integrations will succeed, that code will be readable and maintainable over time, and that debugging will be possible.