← Python lessons

Python Try Except: Catching Errors with else and finally

try and except catch an error while your program runs, so it can carry on instead of crashing. else runs when nothing failed; finally always runs.

An error that happens while code runs is an exception. Read Data validation first.

Catch an error with try and except

Put the code that might fail under try. Put what to do instead under except, with the name of the error.

text = "twelve"
try:
    number = int(text)
    print("Got", number)
except ValueError:
    print("Not a whole number:", text)
print("Still running")

int("twelve") raises ValueError. Python skips the rest of the try block and runs the matching except block. Then the program carries on.

Catch different errors

Add one except for each kind of error. Python runs the first one that matches.

def safe_divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        return "can't divide by zero"
    except TypeError:
        return "numbers only"

print(safe_divide(10, 4))
print(safe_divide(10, 0))
print(safe_divide(10, "2"))

To handle two errors the same way, list them in brackets: except (ValueError, TypeError):.

Get the error message with as

except KeyError as error: stores the exception in error. Print it to see what went wrong.

scores = {"ada": 12}
try:
    print(scores["ben"])
except KeyError as error:
    print("Missing key:", error)

For a KeyError, the message is the missing key, 'ben'.

Add else and finally

else runs only when the try block raised nothing. finally runs every time, error or not. Use it for clean-up, such as closing a file.

def read_age(text):
    try:
        age = int(text)
    except ValueError:
        print(f"{text!r} is not a number")
    else:
        print(f"{text!r} is age {age}")
    finally:
        print("checked", text)

read_age("14")
read_age("old")

"14" runs try, then else, then finally. "old" runs try, then except, then finally.

Note: Name the error you expect. A bare except: catches every error, even a typo in a variable name, so it hides bugs. Keep the try block short: only the lines that can fail.

See also: Raising exceptions, Debugging.

Your turn

Add up the answers that are whole numbers. For any other answer, print skip and the answer.

answers = ["7", "seven", "3"]
total = 0
for answer in answers:
    # add four lines: try to add int(answer) to total; on ValueError print "skip" and the answer
    pass
print(total)

Expected output

skip seven
10

Practise this in the free Python course, where every exercise checks your code instantly.