December 5, 2026

Python try, except, else and finally: Small Tests That Show What Really Runs

A safety net stretched beneath an empty trapeze platform

A function that divided by zero returned the string "swallowed" and raised no error at all. The cause was one return statement inside a finally block, and it is the kind of bug that slips through testing because nothing ever crashes. Python’s exception handling looks simple on the surface: try, except, maybe finally. Underneath are rules about order, chaining and inheritance that decide whether an error is reported, hidden or turned into a different one. A dozen small tests run on Python 3.13 walk through them, with the official tutorial and reference as the yardstick.

Video: Corey Schafer on YouTube

The four clauses and their order

What each one is for

A full try statement can have four parts. try holds the code that might fail. except handles a matching error. else runs only if try finished without an exception. finally runs no matter what. The Python tutorial on errors says “the finally clause will execute as the last task before the try statement completes.”

A test function that parsed a string with int() used all four:

def f4(x):
    try:
        v = int(x)
    except ValueError:
        return "bad"
    else:
        return f"ok {v}"
    finally:
        pass

f4("7") returned ok 7 and f4("x") returned bad.

Why else exists

The else clause looks redundant, since the success code could sit at the end of the try. The tutorial explains why it should not: using else “avoids accidentally catching an exception that wasn’t raised by the code being protected by the try … except statement.” If the success branch also called something that could raise ValueError, putting it inside try would send that unrelated error to the except ValueError handler and report it as bad input. Keeping try as small as possible, and moving the follow-up work into else, keeps each handler honest about what it is catching.

Open electrical control panel with wires and circuit breakers

finally runs even after return

The order of events

A finally block runs after a return statement has been reached but before the function actually hands back its value:

def f1():
    try:
        return "try"
    finally:
        print("finally ran after return")

Calling it printed the message and then returned "try". That ordering is what makes finally the right place to close files, release locks or delete temporary data. The tutorial describes it as useful for “releasing external resources (such as files or network connections), regardless of whether the use of the resource was successful.”

with does the same job, more safely

For the most common cleanup, closing a file or releasing a lock, a with statement does the work of try and finally in one line. The tutorial says that after a with open(...) block, “the file f is always closed, even if a problem was encountered while processing the lines.” A test that opened a file in a with block and then divided by zero inside it caught the ZeroDivisionError outside and found f.closed was True. A hand-written finally is still the right tool for cleanup that has no context manager, but where one exists, it removes the chance of forgetting the finally altogether.

When finally returns too

The trouble starts when finally has its own return. A function with return "try" in the try block and return "finally" in the finally block returned "finally". The tutorial confirms the rule, “the returned value will be the one from the finally clause’s return statement,” and calls it “confusing and is therefore discouraged.”

The swallowed exception

The test

Worse than overriding a value, a return in finally erases an exception in flight:

def f3():
    try:
        1/0
    finally:
        return "swallowed"

f3() returned "swallowed". The ZeroDivisionError vanished. No traceback, no log line, nothing for a test suite to catch.

Python 3.14 starts warning

This pattern is common enough that the language is moving against it. PEP 765, “Disallow return/break/continue that exit a finally block,” is marked Final for Python 3.14, and states that “CPython will emit a SyntaxWarning in version 3.14.” Its motivation is exactly the test above: “a swallowed exception is more likely to slip through testing, than an incorrect return value.” Running the same code under Python 3.13 with warnings turned into errors (python3 -W error) produced no complaint, because the warning starts with 3.14. On 3.13 and earlier, the only defence is not writing it.

Compressed bales of mixed paper and cardboard waste

Catching too much

Bare except catches exits

A bare except: with no exception type catches everything, including exceptions that are not errors. In the test, try: sys.exit(3) followed by a bare except: printed bare except caught SystemExit, and the program kept running when it had been told to stop.

Exception versus BaseException

The built-in exceptions reference explains the hierarchy. The Exception class is the base for “All built-in, non-system-exiting exceptions.” SystemExit “inherits from BaseException instead of Exception so that it is not accidentally caught by code that catches Exception,” and KeyboardInterrupt, raised by Ctrl+C, does the same “so as to not be accidentally caught by code that catches Exception and thus prevent the interpreter from exiting.”

Switching the test to except Exception: let SystemExit pass straight through with its exit code of 3 intact. The practical rule follows: never write a bare except:, and use except Exception: only at the very top of a program, where logging an unexpected error before exiting is the goal. Everywhere else, catch the specific exception the code expects.

Custom exceptions give callers something to catch

The same reference says user-defined exceptions “should also be derived from this class,” meaning Exception, and the tutorial adds that most are named with an “Error” suffix. A small hierarchy pays off quickly. In the test, a MissingKey exception derived from a ConfigError base class was raised, and an except ConfigError handler caught it, reporting the specific type, MissingKey, and the message. Callers that care only that configuration failed catch the base class; callers that can recover from one specific problem catch the subclass.

Turning one error into another

raise from

Libraries often need to translate a low-level error into one that makes sense to their callers, such as a missing dictionary key into “the config file is missing a port.” The tutorial says the raise statement “allows an optional from clause” for this. In the test, raise RuntimeError("config missing port") from e inside an except KeyError as e block produced an exception whose __cause__ was KeyError('port'). The traceback then prints both errors, joined by the line “The above exception was the direct cause of the following exception,” so nothing is lost.

from None

Sometimes the low-level error is noise. Writing raise RuntimeError(...) from None set __cause__ to None and __suppress_context__ to True, which the tutorial describes as “disabling automatic exception chaining.” Without either form, Python still records the original error as __context__ and prints the less helpful “During handling of the above exception, another exception occurred.” Choosing from e or from None on purpose makes tracebacks say what the author meant.

Adding context without replacing the error

Since Python 3.11 there is a lighter option than wrapping: notes. The tutorial says exceptions “have a method add_note(note) that accepts a string and adds it to the exception’s notes list,” and that “The standard traceback rendering includes all notes, in the order they were added, after the exception.” In the test, a ValueError from int('x') got the note while reading line 12 of settings.ini and was re-raised with a bare raise. The formatted traceback ended with the original message followed by the note, and the exception type stayed ValueError, so existing handlers still caught it.

A pile of colorful plastic balls

Several errors at once

ExceptionGroup and except*

Since Python 3.11, code that runs several tasks at once can report all their failures together. The tutorial describes ExceptionGroup as wrapping “a list of exception instances so that they can be raised together,” and the except* syntax as a way to “selectively handle only the exceptions in the group that match a certain type.”

The test raised one group holding ValueError("a"), TypeError("b") and ValueError("c"). An except* ValueError clause received ['a', 'c'], and a separate except* TypeError clause received ['b']. Both handlers ran for the same raise, which a plain except can never do. This mostly appears in asyncio task groups and parallel jobs, where three of ten downloads failing for three different reasons should produce three different reactions.

Are exceptions slow?

Measured

A common belief is that try blocks are expensive. Timing two million calls of a dictionary lookup gave a more useful picture:

Approach Key present? Time per call
try: d['a'] except KeyError Yes 26.5 ns
try: d['b'] except KeyError No 118.4 ns
d.get('b', 0) No 32.9 ns
d['b'] if 'b' in d else 0 No 35.8 ns

When no exception happened, the try version was the fastest of the four. When the exception fired, it was about four times slower than dict.get(), because building and catching an exception object costs real work.

What that means

Use try when failure is rare, which is the usual case for missing files, network errors and bad input. Use a check such as dict.get() or in when the “failure” is an ordinary, frequent outcome, such as counting words where many keys are new. The numbers are tens of nanoseconds either way, so clarity should decide in all but the tightest loops.

Sources

  • Python documentation, Tutorial, “Errors and Exceptions”: https://docs.python.org/3/tutorial/errors.html
  • Python documentation, “Built-in Exceptions”: https://docs.python.org/3/library/exceptions.html
  • PEP 765, “Disallow return/break/continue that exit a finally block”: https://peps.python.org/pep-0765/

920 Posts

Peter Kalafatis writes and edits X9M8. He holds a bachelor's degree from LIU Post and a master's in Media Studies from The New School, with academic work in the philosophy of science, human behavior, AI, and memetics.

View All Posts

Leave a Reply

Your email address will not be published. Required fields are marked *