Why swallowing Exceptions is a bad idea

Posted by Mike Haller on Monday, January 22. 2007 at 11:56 in Java
Consider the following code

      try {
       // Some code throwing exceptions but you
       // have no idea what to do with each different
       // kind, so you just catch all Exceptions
      }
      catch( Exception e )
      {
         throw new TechnicalException( e.getMessage() );
      }


Most people forget that unchecked runtime Exceptions are also Exceptions. Thus, a catch(Exception) will also catch, for example, a NullPointerException. Now, he creates a TechnicalException with the message of the NullPointerException. This has two major draw backs:

First, it draws the stack trace useless. You won't be able to tell which of the lines in the above code has actually thrown the exception.

Secondly, the message of a NullPointerException is null, which means that the TechnicalException has no additional information. It has no usable information at all. It's absolutely meaningless.

Please please use Exception chaining. Or at least add logging. Just do something.

A slightly better way is this, but it's still horrible:

      try {
       // Some code throwing exceptions but you
       // have no idea what to do with each different
       // kind, so you just catch all Exceptions
      }
      catch( Exception e )
      {
         throw new RuntimeException( "Error while trying to do something", e );
      }


At least, it provides you with the information you need to analyze what happened by viewing the stack traces.

Edit: Btw, The Daily WTF has a nice example on how to NOT do it.

sujeet
Why swallowing Exceptions is a bad idea
=======================================

This is really a very valuable advice. I have struggled many times to figure out what was happening with my exceptions.
Mike
However, there is one caveat when working with distributed systems or tiered software design: the chained (nested) exception is not available in the upper layers or on the other side of the remoting and hence will throw ClassNotFoundExceptions on the other end.

To prevent this, the Exceptions need to be translated. If you do this, make sure to log the original Exception on the layer, e.g. with a logging framework.

Add Comment

Enclosing asterisks marks text as bold (*word*), underscore are made via _word_.
Standard emoticons like :-) and ;-) are converted to images.
E-Mail addresses will not be displayed and will only be used for E-Mail notifications
 
Submitted comments will be subject to moderation before being displayed.
 

About

My name is Mike Haller and I'm a software developer and architect at Bosch Software Innovations in Germany. I love programming, playing games and reading books. I like good food, making photos and learning and mentoring about the craftsmanship of commercial software development. Stack Overflow profile for mhaller

Quicksearch