Catching an Exception Near Its Source

An exception handler is easier to reason about when its protected block contains only the operation whose expected error it will translate.

Source
Anbloq
Language
English
Created
Updated
Chapters
2
Reading time
1 min
In this article2 chapters
  1. Trace an overbroad case
  2. Keep the normal calculation readable

Trace an overbroad case

A function parses a quantity and later formats a report. Both tasks could raise an error of the same general class. Catching both as “invalid quantity” misidentifies the latter. See traceback frames for locating the real step.

Keep the normal calculation readable

Translate the parse error next to parsing and let unrelated failures follow their own contract. A test for the expected exception can keep setup and assertions outside that boundary.[1]

References

  1. Python Software Foundation, Python Tutorial: Errors and Exceptions ↩