smithers' bloggo

Do not eat exceptions

do not eat

When handling an exception, you should always do one of two things:

  1. Re-throw the exception
  2. Log the exception

If you do neither, you are dropping information about an error that has happened. You will never see it in your logs, or anywhere. The error is irretrievable. You have "eaten" the exception.

This is a big code smell, but I've seen it happen many times.

Here are examples of seemingly-innocuous exception handling in Java which are actually very dangerous:

try {
...
} catch (SomeException e) {
throw new IllegalArgumentException("something bad happened");
}
try {
...
} catch (SomeException e) {
log.error("something bad happened");
}

Do not do this! You're hiding vital information about these errors. Here's how to fix these:

try {
...
} catch (SomeException e) {
throw new IllegalArgumentException("something bad happened");
throw new IllegalArgumentException("something bad happened", e);
}
try {
...
} catch (SomeException e) {
log.error("something bad happened");
log.error("something bad happened", e);
}

A try-catch that fails to log or re-throw an exception is generally better off not existing.

By the way, if you both log and re-throw an exception, that's not great either. You're ultimately printing one stack trace two times.

This has been a public service announcement.