Video in progress

Strong Junior ☕ Core Java

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;
  • Exception is very broad: it also hides programmer mistakes like an NPE;
  • inside a transaction, Spring doesn't see the error and commits.

Better options:

  1. Don't catch it. In many cases, letting the error go up and handling it in a global handler is the right call.
  2. Catch the specific type and react in a meaningful way:
    catch (PaymentDeclinedException e) {
        order.markPaymentFailed(e.reason());
    }
    
  3. Wrap it and rethrow, without losing the cause:
    catch (IOException e) {
        throw new ImportFailedException("Fayl o'qilmadi: " + path, e);
    }
    
  4. 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().