typestar

else and finally in Python

Four blocks, four jobs: try, except, else for success, finally for cleanup.

def read_number(text):
    try:
        value = int(text)
    except ValueError:
        print("could not parse")
        return None
    else:
        print("parsed cleanly")
        return value
    finally:
        print(f"done with {text!r}")


print(read_number("42"))
print(read_number("no"))

How it works

  1. else runs only when no exception was raised.
  2. finally runs on every path, including a return.
  3. Keeping the risky line alone in try is the point of else.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
234
Tokens
65
Three-star pace
100 tpm

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

Type this snippet

Step 2 of 3 in Errors in depth, step 63 of 72 in Language basics.

← Previous Next →