Sahaj.blogs
3 Oct 2023 · StudyPhase 1 · Python

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 ValueError or KeyError. A bare except: also catches bugs and even KeyboardInterrupt.
  • raise ValueError("msg") signals an error yourself.
  • Custom exceptions are simple subclasses of Exception.
  • raise NewError(...) from e keeps 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: NoneType

#python#exceptions

Sources

  1. Errors and Exceptions — Python Software Foundation
  2. Built-in Exceptions — Python Software Foundation
  3. The try statement — Python Software Foundation