download

In what order do try, except, else and finally run?

Python~8 minReviewed 29 Oct 2026Free · No sign-in

Question

Predict exactly what this code prints, line by line.

Then add return -1 as the last line of the finally block. What do parse("42") and parse(None) return now?

"CODE · PYTHON"
def parse(text):
    try:
        value = int(text)
    except ValueError:
        print("except")
        return None
    else:
        print("else")
        return value
    finally:
        print("finally")


print(parse("42"))
print(parse("x"))
Show hints (3)
  1. "TWO PATHS"

    Follow parse("42") and parse("x") separately. On each path, which of except and else runs? Can both ever run?

  2. "RETURN WAITS"

    A return inside try, except or else doesn't leave the function at once. Python keeps the value, runs finally, and only then returns.

  3. "THE LAST RETURN WINS"

    A function returns the value of the last return that runs, and finally always runs last. What happens to the value that was waiting, or to an exception nobody caught?

Show checked explanation

try runs first. Then except runs if a matching exception was raised, or else if nothing was raised. finally runs last in every case, even when a block before it returns. So the code prints else, finally, 42, except, finally, None. With return -1 in finally, both calls return -1, and the TypeError from parse(None) is lost.

"SOLUTION · PYTHON"
def parse(text):
    try:
        value = int(text)       # 1. always runs first
    except ValueError:
        print("except")         # 2a. only if int() raised ValueError
        return None
    else:
        print("else")           # 2b. only if nothing was raised
        return value
    finally:
        print("finally")        # 3. always runs last, even after return


print(parse("42"))
print(parse("x"))
"OUTPUT"
else
finally
42
except
finally
None

Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.

Walkthrough

Here is each call, step by step:

calltryexceptelsefinallyreturns
parse("42")int worksskippedprints elseprints finally42
parse("x")ValueErrorprints exceptskippedprints finallyNone

except and else never both run. else runs only when the try block raised nothing.

The tricky part is return. When Python reaches return value in else, it doesn't leave right away. It keeps the value 42, runs finally, and only then returns. That's why finally is printed before 42: the caller prints the result only after the function has finished.

Now add return -1 at the end of finally:

"PYTHON"
    finally:
        print("finally")
        return -1

The function returns the value of the last return that runs, and finally always runs last. So parse("42") returns -1, not 42.

parse(None) is worse. int(None) raises TypeError, which except ValueError doesn't catch. finally runs, prints finally, and its return throws the TypeError away. The caller gets -1 and never sees the error.

Python 3.12 runs this code with no warning. Python 3.14 shows a SyntaxWarning when it compiles a return, break or continue that leaves a finally block (PEP 765).

Common mistakes

  • Putting more code in try than the line that can fail. A ValueError from that extra code is then caught and reported as bad input. Move code that should run only on success to else.
  • Using return, break or continue to jump out of finally. It cancels whatever was pending: the real return value is lost, and any exception disappears silently, even KeyboardInterrupt.
  • Silencing errors with a bare except: or except Exception: pass. Both hide real bugs, such as a typo that raises NameError. A bare except even catches KeyboardInterrupt and SystemExit.

Follow-up questions

  • "How do you raise your own error but keep the original one?" Write raise ConfigError("bad port") from err inside the except block. The new exception stores the original in __cause__. The traceback shows both, joined by "The above exception was the direct cause of the following exception". raise ... from None hides the original on purpose.
  • "Does finally always run?" Almost always. It runs on every way out of try: return, break, continue, or any exception, including KeyboardInterrupt and the SystemExit raised by sys.exit(). It does not run after os._exit(), which ends the process at once, or when the process is killed from outside.
  • "When would you use with instead of finally?" Whenever the resource supports it: files, locks, database connections. with open(path) as f: closes the file on every way out of the block, like a finally, in one line. Keep finally for cleanup that has no context manager.

What a strong answer covers

Gets the exact print order right and explains that return waits for finally. Says why else keeps the try block small, and warns that return in finally hides exceptions, which Python 3.14 flags with a SyntaxWarning.

Open in interactive practice deck →

Original OfferVibe question. Topic idea from The Python Interview Handbook (Nezir Zahirovic, 2023); text, examples and code are our own.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.