typestar

The exception hierarchy in Python

Catch the narrowest class that covers what you can actually handle.

print(ValueError.__mro__)
print(issubclass(FileNotFoundError, OSError))


def convert(text):
    try:
        return int(text)
    except ValueError as exc:
        return f"not a number ({exc.args[0][:18]}...)"
    except TypeError:
        return "wrong type entirely"


print(convert("12"), convert("x"), convert(None))
try:
    raise KeyError("missing")
except LookupError as exc:
    print("LookupError caught", type(exc).__name__)

How it works

  1. Exception catches errors; BaseException also catches exits.
  2. The order of except blocks matters: narrowest first.
  3. __mro__ shows why one class catches another.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
392
Tokens
106
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 64 seconds.

Type this snippet

Step 1 of 3 in Errors in depth, step 62 of 72 in Language basics.

← Previous Next →