Video in progress
Why is "swallowing" an error with catch (Exception e) {} dangerous?
The error disappears: the system keeps running in a wrong state, there's no trace in the log, and the problem shows up somewhere else, much later, in a form whose cause you can't find.
📖 Answer
try {
payment.charge(order);
} catch (Exception e) {
// I'll look at it later
}
order.markPaid(); // "paid" even if the money wasn't charged
A catch like this is often written as "temporary" and stays for years. The consequences:
- the user gets an order they haven't paid for;
Exceptionis very broad: it also hides programmer mistakes like an NPE;- inside a transaction, Spring doesn't see the error and commits.
Better options:
- Don't catch it. In many cases, letting the error go up and handling it in a global handler is the right call.
- Catch the specific type and react in a meaningful way:
catch (PaymentDeclinedException e) { order.markPaymentFailed(e.reason()); } - Wrap it and rethrow, without losing the cause:
catch (IOException e) { throw new ImportFailedException("Fayl o'qilmadi: " + path, e); } - If you really can ignore it, write the reason in a comment and at least do a
log.debug.
Swallowing InterruptedException is a separate mistake: if you catch it, restore the flag with Thread.currentThread().interrupt().
Sign up to mark studied questions and save your progress.