Python · Exceptions
try/except/else/finally, catching specific exceptions, raising your own, and custom exception classes.
How the four blocks fit together:
try: code that might fail
except E: runs if an E (or subclass) was raised
else: runs only if nothing was raised
finally: always runs (cleanup)
Lessons from today:
- Catch specific exceptions such as
ValueErrororKeyError. A bareexcept:also catches bugs and evenKeyboardInterrupt. raise ValueError("msg")signals an error yourself.- Custom exceptions are simple subclasses of
Exception. raise NewError(...) from ekeeps the original cause attached.
class MarksError(ValueError):
"""Marks outside the allowed range."""
def parse_marks(text):
try:
m = int(text)
except ValueError as e:
raise MarksError(f"not a number: {text!r}") from e
else:
if not 0 <= m <= 100:
raise MarksError(f"out of range: {m}")
return m
finally:
print(f" checked {text!r}")
for raw in ["88", "abc", "140"]:
try:
print("ok:", parse_marks(raw))
except MarksError as e:
print("error:", e, "| cause:", type(e.__cause__).__name__)
Output:
checked '88'
ok: 88
checked 'abc'
error: not a number: 'abc' | cause: ValueError
checked '140'
error: out of range: 140 | cause: NoneTypeSources
- Errors and Exceptions — Python Software Foundation
- Built-in Exceptions — Python Software Foundation
- The try statement — Python Software Foundation