Python Errors and Exceptions · Lesson 97 of 149

Python try else and finally

What you will learn

  • The complete shape of try / except / else / finally
  • What else is for, and why it keeps try small
  • How finally always runs, for cleanup
  • What happens with return, break and uncaught errors
  • A retry pattern with for and else

1. The full statement

A try statement can have four kinds of block:

try:
    ...        # code that might fail
except SomeError:
    ...        # runs if SomeError happened
else:
    ...        # runs if NO error happened
finally:
    ...        # ALWAYS runs

else and finally are optional (but else needs at least one except). Here they all appear:

def parse(t):
    try:
        n = int(t)
    except ValueError:
        print("bad:", t)
    else:
        print("ok:", n)
        return n
    finally:
        print("done with", repr(t))

print(parse("5"))
print(parse("x"))
ok: 5
done with '5'
5
bad: x
done with 'x'
None

For "5": no error, so the else block ran, then finally. For "x": the except block ran, then finally. In both cases finally ran last, and the function returned 5 or None.

The order of events: try → (except or else) → finally.

Quick check: when does `else` run?

Only when the try block finished without an exception.

2. Why else?

You might ask: why not put the success code at the end of try? Because then an error from that code would be caught by the same except, even though it has nothing to do with what you meant to guard.

def risky_after():
    raise ValueError("from success code")

try:
    n = int("5")
    risky_after()
except ValueError as e:
    print("caught", e)
caught from success code

Here the except ValueError was meant to guard only int("5"), but it also caught a bug in risky_after(), and the message was misleading. Moving the follow-up work to else fixes this:

try:
    n = int("5")
except ValueError:
    print("bad")
else:
    try:
        risky_after()
    except ValueError as e:
        print("separate:", e)
separate: from success code

The rule: keep the try block as small as possible, containing only the code you expect might raise the error you catch. Put what depends on its success in else.

3. finally: always runs

The finally block runs no matter what: after success, after a handled error, after an unhandled error, and even when the block is left by return, break or continue. It is meant for cleanup: closing files, releasing locks, disconnecting.

class Res:
    def __init__(self):
        self.open = True

    def close(self):
        self.open = False
        print("closed")

r = Res()
try:
    raise RuntimeError("fail midway")
except RuntimeError as e:
    print("caught", e)
finally:
    r.close()
print(r.open)
caught fail midway
closed
False

If the error is not handled, finally still runs first, and then the error continues upward:

try:
    try:
        raise KeyError("k")
    finally:
        print("cleanup before crash")
except KeyError:
    print("it still propagated")
cleanup before crash
it still propagated

With return, the finally block runs before the function actually returns:

def f():
    try:
        return "try"
    finally:
        print("finally runs before return")

print(f())
finally runs before return
try

Inside a loop, finally runs on every pass, including when continue or break leaves the block:

for i in range(3):
    try:
        if i == 1:
            continue
        print("body", i)
    finally:
        print("cleanup", i)
body 0
cleanup 0
cleanup 1
body 2
cleanup 2

(The with statement, lesson 14.6, is a tidier tool for cleanup built on this idea.)

4. The return-in-finally trap

A return inside finally overrides any earlier return, and even swallows an exception:

def g():
    try:
        return "try"
    finally:
        return "finally"

print(g())
finally

Avoid return, break or continue inside finally. Use finally only for cleanup.

5. All the pieces together

Block Runs when Typical use
try always starts the risky operation (keep it small)
except the matching error happened recover, report, or convert
else try finished without error work that depends on success
finally always, last cleanup

You can also use try / finally without any except, when you only need cleanup and want the error to continue upward.

6. Retrying with for ... else

A loop can also have an else clause (lesson 6.3): it runs when the loop finishes without break. Combined with try / else, it gives a tidy retry:

for attempt in range(1, 4):
    try:
        if attempt < 3:
            raise ConnectionError("down")
    except ConnectionError as e:
        print("attempt", attempt, "failed:", e)
    else:
        print("attempt", attempt, "worked")
        break
else:
    print("gave up")
attempt 1 failed: down
attempt 2 failed: down
attempt 3 worked

The break in the inner else stops the loop on success, so the loop's else ("gave up") is skipped. If all three attempts had failed, the loop's else would run.

Worked example: sending messages and retrying

A Connection must always be closed, whether the send works or fails. A separate retry function calls an action up to a number of times.

class Connection:
    opened = 0

    def __init__(self):
        Connection.opened += 1
        self.open = True

    def send(self, msg):
        if msg == "bad":
            raise ValueError("cannot send 'bad'")
        return f"sent {msg}"

    def close(self):
        self.open = False


def deliver(msg, log):
    conn = Connection()
    try:
        result = conn.send(msg)
    except ValueError as e:
        log.append(f"failed: {e}")
        return False
    else:
        log.append(result)
        return True
    finally:
        conn.close()
        log.append(f"closed after {msg!r}")


log = []
print(deliver("hello", log))
print(deliver("bad", log))
for line in log:
    print(" ", line)
print(Connection.opened)


def retry(action, times=3):
    for attempt in range(1, times + 1):
        try:
            value = action(attempt)
        except ConnectionError as e:
            print(f"attempt {attempt} failed: {e}")
        else:
            print(f"attempt {attempt} worked")
            return value
    print("gave up")
    return None


def flaky(n):
    if n < 3:
        raise ConnectionError("server down")
    return "data"


def always_down(n):
    raise ConnectionError("down")


print(retry(flaky))
print(retry(always_down, 2))
True
False
  sent hello
  closed after 'hello'
  failed: cannot send 'bad'
  closed after 'bad'
2
attempt 1 failed: server down
attempt 2 failed: server down
attempt 3 worked
data
attempt 1 failed: down
attempt 2 failed: down
gave up
None
Part What it shows
return inside except and else each path returns, yet finally still runs and closes the connection
finally both connections are closed, one after success and one after failure
else in retry the success path returns only when no error occurred
the code after the loop runs only when every attempt failed

The connection is simulated; no network is used. In a real program you would also wait between attempts (lesson 17.1).

Common mistakes

  • A big try block, so unrelated errors are caught.
  • Success code at the end of try instead of in else.
  • return, break or continue inside finally, which can hide errors.
  • Cleanup code placed after the try statement, where it is skipped if an error is not handled.
  • Expecting else to run after an error.
  • Forgetting that finally runs before the function returns.

Key takeaways

  • else runs only if try raised nothing; use it for work that depends on success, to keep try small.
  • finally always runs, last, even with return, break, continue or an uncaught error: use it for cleanup.
  • Never return inside finally.
  • try / finally without except is valid for cleanup only.
  • Loops have an else too, handy in retry code.

Practice

1. In what order do these run when no error occurs: try, except, else, finally?

Show answer

try, else, finally. The except block is skipped.

2. Why put follow-up code in else instead of at the end of try?

Show answer

So that errors from that code are not caught by the except meant for the risky line only.

3. Does finally run if the try block executes return?

Show answer

Yes. It runs just before the function returns.

4. What does g() return?

def g():
    try:
        return 1
    finally:
        return 2
Show answer

2. The return in finally overrides the earlier one. Avoid this.

5. Is try: ... finally: ... without except allowed? What happens to an error?

Show answer

Yes. The finally block runs and then the error continues upward.

6. When does the else of a for loop run?

Show answer

When the loop finishes normally without hitting break.