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.

=======================================
This is really a very valuable advice. I have struggled many times to figure out what was happening with my exceptions.
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.