Statement

try / except / else / finally

try runs code that might fail; except catches the error so your program can react, and else and finally add extra steps.

BeginnerEvery example below runs in your browser. Change the code and press Run.

try: # code that might fail except SomeError as e: # runs if that error happened else: # optional: runs if no error happened finally: # optional: always runs

When something goes wrong, Python raises an exception (an error object) and, if nobody handles it, stops the program. A try block lets you catch that exception and decide what to do instead: show a friendly message, use a default value, or try again.

Put the risky lines in try. Each except names an error type it handles, such as ValueError or ZeroDivisionError. The optional else runs only when no error happened, and finally runs in every case, which makes it the place for clean-up.

Catch the errors you expect and nothing more. A bare except: also catches typos in your own code and even Ctrl+C, which hides real bugs.

Examples

1Catch a division by zero

Pythoneditable
def share(total, people):
    try:
        return total / people
    except ZeroDivisionError:
        return 0

print(share(90, 3))
print(share(90, 0))
Output
30.0
0

2Turn text into a number safely

else holds the code that should only run when the conversion worked.

Pythoneditable
for text in ["42", "4.5", "ten"]:
    try:
        n = int(text)
    except ValueError:
        print(repr(text), "is not a whole number")
    else:
        print(repr(text), "->", n * 2)
Output
'42' -> 84
'4.5' is not a whole number
'ten' is not a whole number

We print our own message instead of Python's, whose wording can change between versions.

3Look at the error with as

Pythoneditable
prices = {"tea": 2.5, "cake": 4.0}
try:
    print(prices["coffee"])
except KeyError as e:
    print("Missing key:", e.args[0])
Output
Missing key: coffee

as e gives you the exception object. e.args holds the values it was created with.

4Several error types

Python checks the except blocks from top to bottom and runs the first one that matches.

Pythoneditable
def parse_ratio(text):
    try:
        a, b = text.split("/")
        return int(a) / int(b)
    except ValueError:
        return "not a ratio like 3/4"
    except ZeroDivisionError:
        return "bottom number is 0"

print(parse_ratio("3/4"))
print(parse_ratio("3/0"))
print(parse_ratio("hello"))
Output
0.75
bottom number is 0
not a ratio like 3/4

5finally always runs

Pythoneditable
def load(step_fails):
    print("open connection")
    try:
        if step_fails:
            raise RuntimeError("download failed")
        print("download ok")
    except RuntimeError as e:
        print("error:", e)
    finally:
        print("close connection")

load(False)
load(True)
Output
open connection
download ok
close connection
open connection
error: download failed
close connection

For files, with statement does this clean-up for you.

Common mistakes

Catching everything with a bare except

except: or except Exception: with pass swallows every error, including a misspelled variable name, so the bug stays hidden. Catch the specific type you expect, such as except ValueError:.

Putting too much inside try

Keep the try block short: only the line that can fail. Code that should run after success belongs in else, so an error there is not mistaken for the one you meant to catch.

Questions people ask

How do I catch several exceptions in one except?

Put them in a tuple: except (ValueError, TypeError) as e:.

How do I print the error message?

Use except SomeError as e: then print(e). type(e).__name__ gives the error's name.

What is the difference between else and finally?

else runs only when the try block had no error. finally runs every time, error or not, even after return.

How do I raise my own error?

Use raise statement: raise ValueError("age must be positive").

Spotted a mistake on this page? Tell us