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
Exceptioncatches errors;BaseExceptionalso catches exits.- The order of except blocks matters: narrowest first.
__mro__shows why one class catches another.
Keywords and builtins used here
asconvertdefexceptintissubclassprintraisereturntrytype
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.
Step 1 of 3 in Errors in depth, step 62 of 72 in Language basics.