One of my pet peeves is programmers swallowing exceptions. I see code like this all the time.
public int getValue() {
int value = 0;
try {
value = compute(...);
} catch (ComputeException ce) {}
return value;
}
I can sympathize, because Java has too many annoying checked exceptions, and you might not be at liberty to throw them due to interface restrictions. Sometimes developers reason that it's permissible to ignore the exception because the exception will never, ever, be thrown. That may or may not be true. In either case, just throw some sort of runtime exception and let the client deal with it.
public int getValue() {
try {
int value compute(...);
return value;
} catch (ComputeException ce) {
throw new RuntimeException(ce);
}
}
It's almost always better to say, "hey, I have no idea what to do here, you deal with it" than "it should be OK if I just ignore this".
A place where you'll often see exceptions swallowed is with code invoking blocking methods. You might be calling some blocking method that throws an InterruptedException. It's very tempting to swallow an interruption request, but unless you know the thread's interruption policy you should either propagate the InterruptedExcetion or restore the interrupted status, like this example shows (from Brian Goetz).
public Task getNextTask(BlockingQueue<Task> queue) {
boolean interrupted = false;
try {
while (true) {
try {
return queue.take();
} catch (InterruptedException e) {
interrupted = true;
// fall through and retry
}
}
} finally {
if (interrupted)
Thread.currentThread().interrupt();
}
}
This approach allows your code to perform cleanup (such as leaving the data in a consistent state) and/or continue but lets the thread deal with the interruption accordingly because the interrupt is not lost. Again, ignoring something because you don't know what to do with it is almost always a bad idea.













How about methods closing anything, like a connection, socket, data source, etc.? I do believe that these should nether throw exceptions, no matter what. But that's an exception rather than a rule
Posted by: Anton | May 19, 2009 at 01:16 PM