Back to Ruff

Invalid Exception Caught

crates/ty_python_semantic/resources/lint_docs/invalid-exception-caught.md

0.15.18957 B
Original Source

What it does

Checks for exception handlers that catch non-exception classes.

Why is this bad?

Catching classes that do not inherit from BaseException will raise a TypeError at runtime.

Example

python
import random


def might_raise() -> float:
    return 1 / random.choice([0, 1, 2, 3, 4, 5])


try:
    might_raise()
except 1:  # error
    ...

Use instead:

python
import random


def might_raise() -> float:
    return 1 / random.choice([0, 1, 2, 3, 4, 5])


try:
    might_raise()
except ZeroDivisionError:
    ...

References

Ruff rule

This rule corresponds to Ruff's except-with-non-exception-classes (B030)