Which exception handling anti-patterns fail interviews in Java, and how do you avoid them?
There are a handful of patterns that interviewers spot straight away, and they all come from the same mistake, which is throwing away the information about what went wrong.
public class Main {
public static void main(String[] args) {
// Anti-pattern 1: swallowing the exception entirely.
try {
riskyStep();
} catch (Exception e) {
// Nothing here. The failure has vanished.
}
// Anti-pattern 2: catching the broadest type you can find.
try {
riskyStep();
} catch (Throwable e) {
// This also catches Errors, which you should never catch.
}
}
static void riskyStep() {
throw new IllegalStateException("something went wrong");
}
}
Here are the patterns to avoid, with the fix for each one.
Swallowing the exception. An empty catch block throws the failure away. The program carries on as if the call had worked, and usually with a broken state. The fix is to do something with it, at the very least writing it to a log.
Catching Exception or Throwable too widely. Catching Exception catches every runtime problem, including the ones that are really bugs in your code. Catching Throwable also catches the errors that mean the runtime itself is in trouble. The fix is to catch the most specific type that you can actually handle.
Catching Exception and rethrowing the same object. That loses the original stack trace, because the stack trace is worked out when the exception is created. The fix is to wrap it in a new exception and pass the original along as the cause.
Using exceptions for normal flow. Throwing an exception to say "not found" when a simple check would do is slow and hard to read. The fix is to return a value that says so, such as an empty optional, and to keep the exceptions for the failures.
Printing the stack trace instead of logging it. The method printStackTrace writes to the console and it goes nowhere in a server. The fix is to use a logger, which writes where the people who need it will look.
The next question in this topic looks at the most common one of these in more detail.