Dr. Dobb's Journal January, 2006
Tip #5: Exceptions May Be Poisonous
Some people eat exceptions. Their rotten delicacy looks something like this:
try{
// something that generates an exception
...
} catch( Exception x ) {
// do nothing
}
Sadly, this is more common than good folks should stand for. Eating exceptions usually assumes that only a certain kind of exception will ever be caught, and therefore, can be ignored. This is bad for several reasons.
For one thing, it breaks the old maxim to use exceptions only for exceptional cases. For another, it catches unanticipated, real exceptions. Even if these real exceptions dont cause the system to crash immediately, the app is now in an unstable state. Heaven help users whose trusted applications are silently destroying or misrepresenting their data.
Modern Java IDEs make the job of printing the stacktrace as easy as typing a hotkey. Theres simply no excuse for doing anything less than this:
try{
// something that generates an exception
...
} catch( Exception x ) {
// x.printStackTrace();
}
If you think you've found the rare exception where catching the exception should be done as a part of control flow, think again. The mistake goes something like this:
try{
Socket mySocket = new Socket(...);
while( true ) {
// Do some repeating task
...
if (socket.isClosed()) {
throw new Exception("socket closed");
}
}
} catch( Exception x ) {
if (x.getMessage().equals( "secret-catcher-msg") {
// write some normal program code here
...
return; // merrily
}
}
The problems with this include:
You can accomplish the same thing by catching all exception types inside your loop, then returning the appropriate message for different kinds of exceptions caught, like this:
while( true ) {
try{
// something that generates an exception
...
} catch( Exception x ) {
if (x instanceof MyExceptionType) {
// Do something special
...
}
else {
// Do the standard thing
...
}
}
}
Logging is the obvious way to capture nonfatal exceptions. Its an appropriate thing to do when you dont know how to handle an exception (that you know you must handle). Logging an exception basically says to users, Something went wrong but its been handled. If things go wrong, heres a little more info.
Like paranoid spies trying to cover their tracks, if theres any doubt about how to handle an exception after logging it, kill the application. Better a dead app with a nice logged message than one giving you false dataor one just screwing up your data.
Benjamin Booth
http://www.benjaminbooth.com/