Skip to content

Python · correctness

no-fat-try-blocks

python:no-fat-try-blocks

Keep a `try` body narrow enough to identify which operation a handler covers.

Code
SARJ007
Default
error
Fix
none
Languages
python

Why

A broad `try` body can route unrelated failures into a handler that was written for one operation.

Fix

Move unrelated operations outside the `try`, or split the body into smaller exception boundaries.

Before / after

Executed by this rule’s unit tests.

Before

One handler covers four raising operations

app/service.py · focus
try:
    a = load_a()
    b = load_b()
    c = load_c()
    d = load_d()
except ValueError:
    recover()

After

Handler covers only the relevant operation

app/service.py · focus
a = load_a()
b = load_b()
c = load_c()
try:
    d = load_d()
except ValueError:
    recover()

Limits

  • Only top-level statements containing plausibly raising operations count toward the limit of three.
  • Generated files, `try` statements with `else` or `finally`, and handlers that always re-raise are excluded.