the full guide

Try and except: handling errors

Keep a program running when something goes wrong, as real data always will.

15 min Beginner

What you need: The earlier pages of this course. Nothing to install.

try and except

try_except.py
values = ["10", "20", "abc", "40"]
total = 0

for value in values:
    try:
        total += int(value)
    except ValueError:
        print("Skipping a bad value:", value)
    finally:
        pass        # Runs every time, error or not

print("Total:", total)

Output

Skipping a bad value: abc
Total: 70

Without try, the program would stop at “abc”. Name the error you expect, so that surprises aren't hidden.

raise_error.py
def set_age(age):
    if age < 0:
        raise ValueError("Age can't be negative")
    return age

try:
    set_age(-5)
except ValueError as error:
    print("Problem:", error)

Output

Problem: Age can't be negative
ErrorWhen it happens
ValueErrorRight type, wrong value: int("abc")
TypeErrorWrong type: "a" + 1
KeyErrorThat key isn't in the dictionary
IndexErrorThat position isn't in the list
ZeroDivisionErrorDividing by zero
FileNotFoundErrorThat file doesn't exist

Finished reading?