Skip to content
Ameen Abozaid
In reviewJNR-006-L04

Logging exceptions well

  • Lesson 4 of 7
  • 11 min read
  • Junior
On This Lesson 4 topics

The content for this lesson is written and waiting for review. The outline below shows what it covers. It will be published once it is approved.

In this lesson

log an exception once, with its stack trace.

Planned topics

  • Pass the exception as the last argument: log.error("Payment failed for {}", id, e).
  • Do not use e.getMessage() alone; you lose the stack trace.
  • Log it once, at the place that handles it.
  • Do not log and rethrow: the same error then appears many times.
  • Either handle it (log) or pass it up (throw), not both.
Draft outline details

Demonstration

java
try { pay(order); }
catch (PaymentException e) {
    log.error("Payment failed for order {}", order.id(), e);
}

Check your understanding

Why is log-and-rethrow bad?

Show answer

The same error is logged several times and confuses readers.

Practice

Apply this lesson with the module's lab, exercises and quiz.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.