typestar

try, except, finally in Python

Handling failure: catch what you expect, re-raise what you don't.

def safe_divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        return None
    except TypeError as exc:
        raise ValueError(f"bad operands: {exc}")
    else:
        return result
    finally:
        print("attempted division")


half = safe_divide(1, 2)
nothing = safe_divide(1, 0)

How it works

  1. Each except clause targets one exception type.
  2. else runs only when nothing was raised.
  3. finally runs on every exit path.
  4. Catching TypeError re-raises as a clearer error.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
258
Tokens
64
Three-star pace
100 tpm

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

Type this snippet

Step 4 of 7 in Iterators, errors & files, step 47 of 72 in Language basics.

← Previous Next →