Python

Python Exceptions — try, except, else, finally, and raise

Errors are normal in real programs: text that is not a number, a key that is not in a dict, an index past the end of a list. This guide shows how to handle those errors without stopping the program: the main try and except flow, catching specific exception types and reading the message, the else and finally ordering, raising an error on purpose with a custom exception class, chaining a new error to its cause, and the exact messages for two common errors.

Written November 12, 2026 · Tested with Python 3.12.3 · 9 min read

By the end of this guide
  • The main program: try, except, else, and finally together
  • Catching specific types and reading the message
  • The else and finally ordering, step by step
  • Raising errors and a custom exception class

Written November 12, 2026

Tested with Python 3.12.3

What this guide is

An exception is an error signal raised while a program runs. When code raises an exception and nothing handles it, the program stops and prints a traceback with the error type and message. A try block lets you handle the error instead: code after the failing line inside the try block is skipped, a matching except block runs, and the program continues after the whole statement. The goal is not to hide errors. The goal is to decide, for each kind of failure you can foresee, whether the program can recover, should report and move on, or should stop with a clearer message.

The main program: try, except, else, and finally together

The try clause holds the code that can fail. The except clause names the error type to catch. The else clause runs only when the try code raised nothing. The finally clause runs either way, before any return takes effect:

Python
def parse_age(text):
    try:
        age = int(text)
    except ValueError:
        return "not a number"
    else:
        return f"age {age}"
    finally:
        print("done")
print(parse_age("42"))
print(parse_age("abc"))

The exact output:

Command
done
age 42
done
not a number

The finally line prints first in each pair. That order surprises many readers: the return value is chosen in the try or except block, then the finally block runs, and only then does the caller receive the value and print it. For the good input, int succeeds, the else block chooses the return value, finally prints done, and the caller prints the age. For the bad input, int raises ValueError, the except block chooses the other return value, finally prints done again, and the caller prints that message. One finally block serves both paths, which is why it suits closing a file, releasing a lock, or printing a closing note that must happen on success and on failure alike.

Catching specific types and reading the message

Catch the specific type you expect, not a broad type that could hide unrelated bugs. The as form binds the exception object, and printing it gives the message the interpreter built. Different types can have different handlers in the same statement, and Python uses the first handler that matches:

Python
scores = {"ana": 10, "bo": 20}
items = [100, 200]
def fetch(key, index):
    try:
        return scores[key] + items[index]
    except KeyError as e:
        return f"missing key {e}"
    except IndexError as e:
        return f"bad index: {e}"
print(fetch("ana", 0))
print(fetch("cy", 0))
print(fetch("ana", 5))
try:
    int("12x")
except ValueError as e:
    print(f"ValueError: {e}")

The exact output:

Output
110
missing key 'cy'
bad index: list index out of range
ValueError: invalid literal for int() with base 10: '12x'

A missing dict key raises KeyError, and its message is the key itself in quotes. A list index past the end raises IndexError, with the plain message shown. A bad integer string raises ValueError, with a message that names the input. Because each handler names one type, a third kind of error inside fetch would not be caught by either handler and would still stop the program, which is the right outcome for a bug you did not foresee. Catching Exception itself, or using a bare except with no type, catches programming errors as well and makes them hard to find.

The else and finally ordering, step by step

The two optional clauses have fixed places in the order. The else block runs after a clean try block and before finally. The except block and the else block never both run for the same try statement:

Python
def run(value):
    print("start")
    try:
        n = int(value)
    except ValueError:
        print("except block")
    else:
        print(f"else block: {n}")
    finally:
        print("finally block")
    print("after")
run("7")
print("---")
run("x")

The exact output:

Output
start
else block: 7
finally block
after
---
start
except block
finally block
after

Keeping success code in else, rather than at the end of try, narrows the try block to the one line that can raise. If the success code itself raised the same error type, a wide try block would catch its error by mistake and report the wrong cause. The line after the whole statement runs in both cases shown, because the exception was handled. When no handler matches, that line does not run: control leaves the function or program at once, after finally has run.

Raising errors and a custom exception class

The raise statement starts an exception on purpose. A function raises when its caller passed a value the function cannot work with, and stopping early with a clear message beats returning a sentinel that callers forget to test. A class that inherits from Exception gives that error its own name, so callers can catch exactly that problem:

Python
class TooSmallError(Exception):
    pass
def check(n):
    if n < 10:
        raise TooSmallError(f"value {n} is below 10")
    return f"value {n} ok"
try:
    print(check(3))
except TooSmallError as e:
    print(f"caught: {e}")
print(check(15))

The exact output:

Output
caught: value 3 is below 10
value 15 ok

The custom class is empty: the name and the inheritance do the work. The message is built at the raise site, where the bad value is known, and the handler reads it back from the exception object. Use a built-in type such as ValueError when its meaning fits, so other code that already catches that type keeps working. Use a custom class when the problem is specific to your program and callers should be able to catch it without also catching unrelated errors of the same built-in type.

Chaining: keep the original cause

When a handler cannot fix a failure but can explain it in higher-level terms, it raises a new exception. Writing from and the original exception after the new one records the first error as the cause of the second. Callers then catch the new type, and the cause is still available for reporting:

Python
def load(text):
    try:
        return int(text)
    except ValueError as e:
        raise RuntimeError("load failed") from e
try:
    load("nope")
except RuntimeError as e:
    print(f"outer: {e}")
    print(f"cause type: {type(e.__cause__).__name__}")
    print(f"cause: {e.__cause__}")

The exact output:

Output
outer: load failed
cause type: ValueError
cause: invalid literal for int() with base 10: 'nope'

Without the from clause, Python still notes that a new exception was raised during handling of another, but marks it as context rather than a stated cause. A bare raise inside a handler does the opposite job: it re-raises the same exception after some local work such as logging, so the original error, with its original traceback, continues outward. Choose chaining when you are translating an error for a different layer, and a bare re-raise when the same error should simply keep going.

Two common errors, with their exact messages

Most beginner tracebacks are a small set of types. Two of the most common are a failed conversion and a missing key. Reading the last line of a traceback gives the type and message; handling the type lets the program report the same facts and continue:

Python
try:
    int("hello")
except ValueError as e:
    print(f"ValueError: {e}")
d = {"a": 1}
try:
    print(d["b"])
except KeyError as e:
    print(f"KeyError: {e}")

The exact output:

Output
ValueError: invalid literal for int() with base 10: 'hello'
KeyError: 'b'

Left unhandled, the first line alone stops a program with a traceback ending in that same ValueError line and a nonzero exit status. The message tells you the input that failed, in quotes, so a quick look at the input usually shows the fix: strip spaces, check for empty text, or fall back to a default. The KeyError message is only the missing key, which points at a name mismatch or a record built without that field. Testing membership with in, or reading with the dict get method and a default, avoids the error when a missing key is an expected case rather than a bug.

Which form for which job

Job Form Why
Mark code that can fail try Control jumps to a matching handler instead of stopping
Handle one foreseen failure except with a specific type Other error types still surface as bugs
Read why an error happened except Type as e The exception object carries the message
Run code only on success else It runs only when the try block raised nothing
Run code on every path finally It runs on success, on handled errors, and before a return
Signal a bad value early raise with a built-in type Callers already know how to catch it
Name a program-specific problem A custom class inheriting Exception Callers can catch that problem alone
Translate an error for another layer raise New from original The new type is caught and the cause is kept
Let an error continue after local work A bare raise in a handler The same exception keeps its traceback

Checklist

  • Before catching an error, name the specific type you expect; leave other types to stop the program and show their traceback.
  • Before putting success code at the end of try, move it to else when it could raise the same type you are catching.
  • Before returning from try or except, remember finally runs first; put cleanup there, not on one path only.
  • Before returning a sentinel for a bad value, raise an error with a message that names the value.
  • Before adding a custom exception, try a built-in type whose meaning fits; add the class when callers need to catch your problem alone.
  • Before swallowing an error in an empty handler, at least report it; a silent handler turns a bug you could have found into wrong results.

Sources

Keep Exploring