Coding

Python Exception Handling: try, except, else, finally Explained

Python exception handling uses the try statement: code that might fail goes in try, the response goes in an except clause for a specific exception type, and cleanup that must always run goes in finally. An exception that no except clause matches keeps travelling up the call stack and ends the program with a traceback.

try:
    value = int("forty-two")
except ValueError:
    value = 0
else:
    print("parsed fine")
finally:
    print("always runs")

This prints always runs and leaves value as 0, because int("forty-two") raises ValueError. The else block is skipped.

How try, except, else and finally run

The order is defined in the language reference:

  1. The try clause runs. If nothing is raised, the except clauses are skipped.
  2. If something is raised, the rest of the try clause is skipped. The first except clause whose class matches the exception (or a base class of it) runs. At most one handler runs.
  3. If no except clause matches, the exception is passed on to outer try statements. With no handler anywhere, it is an unhandled exception and execution stops with an error message.
  4. else runs only if the try clause raised nothing and was not left by return, break or continue.
  5. finally runs last in every case.

Two details trip people up. First, handlers only cover the try clause: an exception raised inside an except or else block is not caught by the sibling except clauses of the same statement. Second, matching is by inheritance, so order matters. The documentation's example with classes B, C (a subclass of B) and D (a subclass of C) prints B, C, D when the clauses are ordered except D, except C, except B. Reverse them and it prints B, B, B, because the first matching clause wins. Put the most specific class first.

Catch specific exceptions, not everything

List the exception types you expect, and handle each one on purpose:

try:
    with open("settings.txt") as handle:
        count = int(handle.readline().strip())
except FileNotFoundError:
    count = 0
except ValueError:
    print("First line is not a whole number")
    raise

FileNotFoundError is a subclass of OSError and is raised when a file or directory is requested but does not exist. To handle several types the same way, pass a tuple: except (ValueError, TypeError):. From Python 3.14 the parentheses can be dropped when you do not use as; on older versions they are required.

To use the exception object, add as:

try:
    raise Exception("spam", "eggs")
except Exception as error:
    print(error.args)

Example output:

('spam', 'eggs')

The name after as is deleted when the except clause ends, so copy it somewhere if you need it afterwards.

What a broad except Exception is for

The documentation says Exception catches almost everything but that being specific is better practice. If you must catch it, for example at the top of a program or a worker loop, do not swallow the error. Report it and re-raise with a bare raise:

except Exception as error:
    print(f"Unexpected {error=}, {type(error)=}")
    raise

A bare raise inside an except block re-raises the exception being handled, traceback intact.

Why Ctrl+C and sys.exit() are not caught by except Exception

All built-in exceptions descend from BaseException. Most of them go through its subclass Exception. Three that do not are KeyboardInterrupt, SystemExit (raised by sys.exit()) and GeneratorExit. The documentation says KeyboardInterrupt inherits from BaseException so that code catching Exception does not accidentally prevent the interpreter from exiting. The same reasoning applies to SystemExit. An expression-less except: does match them, which is one more reason to avoid it. If you use one, it must be the last except clause.

When to use else and finally

Use else to keep the try clause small. The tutorial says it avoids accidentally catching an exception that was not raised by the code being protected:

try:
    reading = float(text)
except ValueError:
    print("not a number")
else:
    print(reading * 2)   # an error here is NOT caught by the except above

Use finally for cleanup that must happen regardless of the outcome. If an exception was not handled, it is saved, finally runs, and the exception is re-raised at the end of the finally clause. A return in try also triggers finally on the way out.

Do not put return, break or continue inside finally. It discards any saved exception, so the error disappears silently. The documentation's example:

def bool_return():
    try:
        return True
    finally:
        return False

Calling bool_return() returns False. Since Python 3.14 the compiler emits a SyntaxWarning for this pattern (PEP 765).

Use with for files and other resources

For objects with built-in cleanup, a with statement is shorter than try/finally. In the tutorial's words, after the statement runs the file is always closed, even if a problem was encountered while processing the lines:

with open("myfile.txt") as handle:
    for line in handle:
        print(line, end="")

Check an object's documentation to see whether it supports with.

How to raise an exception

Use raise with an exception class or instance. raise ValueError is shorthand for raise ValueError(). Pass a message so the traceback explains what went wrong:

def set_age(age):
    if age < 0:
        raise ValueError(f"age must be 0 or more, got {age}")
    return age

Chain exceptions with raise from

If you catch a low-level error and raise a higher-level one, link them with from:

class ConfigError(Exception):
    pass

def load(config, key):
    try:
        return config[key]
    except KeyError as error:
        raise ConfigError(f"missing {key!r}") from error

The original error is stored in __cause__ of the new one. The traceback then contains the line The above exception was the direct cause of the following exception:. If you raise a new exception inside an except block without from, Python still links them through __context__ and prints During handling of the above exception, another exception occurred:. To hide the old error from the display, use raise ConfigError(...) from None. The old exception stays available in __context__ for debugging.

Define your own exception class

The ConfigError class above is a complete custom exception. The built-in exceptions reference says user-defined exceptions should derive from Exception or one of its subclasses, not from BaseException. A shared base class for a library lets callers catch all of its errors with one except clause.

Add context with add_note

An exception has an add_note() method that attaches a string to the exception. The standard traceback prints notes after the exception message, in the order added:

try:
    raise TypeError("bad type")
except Exception as error:
    error.add_note("while reading row 12")
    raise

Example output ending:

TypeError: bad type
while reading row 12

Handling several errors at once: ExceptionGroup and except*

An ExceptionGroup wraps a list of exception instances so they can be raised together. Catch them with except*, which handles only the members that match and lets the rest propagate:

try:
    raise ExceptionGroup("eg", [ValueError(1), TypeError(2), OSError(3), OSError(4)])
except* TypeError as group:
    print(group.exceptions)
except* OSError as group:
    print(group.exceptions)

Example output, followed by a traceback for the unhandled ValueError group:

(TypeError(2),)
(OSError(3), OSError(4))

A try statement can use except or except* clauses, not both. except*: without a type is a syntax error, and return, break and continue cannot appear inside an except* clause.

Common mistakes

  • Wrapping too much in try. Keep only the lines that can raise the exception you handle. Move the rest to else.
  • Swallowing errors. except Exception: pass hides bugs. Handle the error, or log it and re-raise.
  • Wrong clause order. A base class listed first catches its subclasses, so later clauses never run.
  • Returning from finally. It cancels the exception in flight.

Frequently asked questions

What is the difference between else and finally in a Python try statement?
The else clause runs only when the try clause finished without raising an exception and without leaving through return, break or continue. The finally clause runs every time, whether or not an exception occurred, and also when the try clause exits through return, break or continue. Use else for code that should run only on success, and finally for cleanup.
Should I catch Exception or a specific exception?
Catch the most specific exception you can handle. The Python documentation calls Exception a wildcard that catches almost everything and says it is good practice to be as specific as possible. If you do catch Exception, log or report the error and re-raise it with a bare raise.
Why does Ctrl+C not get caught by except Exception?
KeyboardInterrupt and SystemExit inherit from BaseException, not Exception. Python does this on purpose, so that code catching Exception cannot accidentally stop the interpreter from exiting.
How do I stop Python showing the original error when I raise a new one?
Use raise NewError(...) from None. It sets the new exception's __suppress_context__ to True, so the traceback shows only the new error. The old exception is still available in __context__ for debugging.

Sources