Which exception handling anti-patterns fail interviews in Java, and how do you avoid them?
There are four that come up repeatedly, and interviewers tend to spot all of them.
Swallowing the exception — an empty catch block, or one that only prints a message and carries on. The program appears to work while the failure is invisible. Catching Throwable — which also catches OutOfMemoryError and StackOverflowError, the two conditions you must never swallow. Catching Exception broadly and doing nothing meaningful with it, which turns a specific failure into a generic one and loses the information in the stack trace. And using exceptions for control flow, such as throwing an exception to signal a normal, expected outcome that a return value would express more clearly.
The common thread is that all of them discard information at exactly the moment you most need it. The fix in each case is the same shape: catch the narrowest type that you can actually act on, do something useful with it, and either recover or rethrow with the original attached as the cause.
public class Main {
public static void main(String[] args) {
// Anti-pattern 1: swallowing the exception entirely.
try {
risky();
} catch (Exception e) {
// nothing happens - the failure is invisible
}
// Anti-pattern 2: catching Throwable also swallows Errors.
try {
risky();
} catch (Throwable t) {
System.out.println("caught Throwable: " + t.getClass().getSimpleName());
}
// The fix: catch what you can handle, and do something about it.
try {
risky();
} catch (IllegalStateException e) {
System.out.println("recovered from: " + e.getMessage());
}
}
static void risky() {
throw new IllegalStateException("something went wrong");
}
}The output makes the point: the first block prints nothing at all, which is exactly the problem, and the third block turns the same failure into an actionable message.
One related habit to mention in an interview: never log an exception with only its message. Log the exception object itself, so the stack trace is included. A log line reading "connection failed" is nearly useless; a log line containing the exception prints the type, the message and the frames that show where it came from, which is what lets you fix the bug.