Java › Exceptions
What is a common anti-pattern with catching exceptions too broadly (catch (Exception e) or worse, catch (Throwable t)), and why is it generally discouraged?
IntermediateAnswer
Catching an overly broad exception type (Exception, or especially Throwable, which also catches Errors like OutOfMemoryError that generally indicate unrecoverable JVM-level problems) risks silently swallowing exceptions the code has no genuine ability to meaningfully handle, masking real bugs (like an unexpected NullPointerException from a coding mistake being silently caught alongside an intentionally-handled, expected checked exception), making debugging significantly harder since the actual root cause of a problem gets hidden behind generic, non-specific catch-all handling -- best practice catches only the specific exception types the code can genuinely, meaningfully recover from, letting anything else propagate up to a level equipped to handle it (or a global handler) rather than being silently absorbed.
// Anti-pattern: overly broad catch swallows everything, including bugs
try {
processOrder(order);
} catch (Exception e) {
log.error("Something went wrong"); // swallows EVERYTHING, including NullPointerException bugs!
}
// Better: catch only the specific, genuinely-expected/recoverable exception
try {
processOrder(order);
} catch (PaymentDeclinedException e) {
notifyCustomerOfDeclinedPayment(order, e);
}Real-world example A production bug where orders were silently failing without any visible error is eventually traced to a broad catch (Exception e) block that had been quietly swallowing an unrelated NullPointerException bug alongside the specific PaymentDeclinedException the code was actually intended to handle, masking the real defect for months.