The log line without a stack trace
A easy Java puzzle in the exception handling mistakes family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.
Highlighted: line 10. Play this one as a puzzle without the answer.
What is wrong
Only getMessage is logged. For many exceptions the message is null or generic, and the stack trace and cause chain, which show where and why, are not recorded at all. The log reads "charge failed: null".
The fix
How to avoid it next time
Pass the exception object itself to the logger as the last argument so the full stack trace and causes are written.
Want the background? Read Logging with SLF4J in the Java concepts library.
About exception handling mistakes
Swallowed exceptions, lost causes and returns in finally blocks hide failures until the data is already wrong. The program keeps running and nobody knows why the result is missing.
In code review: An empty catch block, a catch that only prints, or an exception rethrown without its cause are all red flags. Log with the exception object and rethrow or handle meaningfully.
More puzzles in this family
Frequently asked questions
What is the bug in "The log line without a stack trace"?
Only getMessage is logged. For many exceptions the message is null or generic, and the stack trace and cause chain, which show where and why, are not recorded at all. The log reads "charge failed: null". The faulty line is line 10: LOG.severe("charge failed: " + e.getMessage());
How do I fix it?
Replace it with: LOG.log(java.util.logging.Level.SEVERE, "charge failed for order " + order, e);. Pass the exception object itself to the logger as the last argument so the full stack trace and causes are written.
How do I catch exception handling mistakes in code review?
An empty catch block, a catch that only prints, or an exception rethrown without its cause are all red flags. Log with the exception object and rethrow or handle meaningfully.
Is there a new puzzle every day?
Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.