Python lesson 27

Try and Except. When Things Go Wrong

Catch the crash and keep the program running.

Attempt, Then Recover

Put the risky code in a try block. If it goes wrong, Python jumps straight to the except block instead of crashing. Name the kind of error you expect, so a different problem is not swallowed silently.

try:
age = int("banana")
except ValueError:
print("That is not a number")

# common ones:
# ValueError. The wrong sort of value
# ZeroDivisionError. Divided by zero
# KeyError. No such key in a dictionary

try:
    age = int("banana")
    print("Age is", age)
except ValueError:
    print("That is not a number!")

print("The program is still running.")

Which Lines Run?

try:
    print("A")
    result = 10 / 0
    print("B")
except ZeroDivisionError:
    print("C")
print("D")

Assemble the Safety Net

A Safe Divider

Run it. The second division would normally kill the program.

def safe_divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        return "Cannot divide by zero"

print(safe_divide(10, 2))
print(safe_divide(10, 0))
print("Still here!")

Check Every Answer

Some of these are numbers and some are not. The loop must survive all of them.

answers = ["12", "seven", "30", "x"]
total = 0
for answer in answers:
    try:
        total = total + int(answer)
    except ValueError:
        print("Skipping", answer)
print("Total:", total)

Say What Went Wrong

Capture the error itself with "as" so you can show the real reason.

scores = {"Nova": 40}

try:
    print(scores["Blaze"])
except KeyError as problem:
    print("No such player:", problem)

print("Carrying on.")

What you can do on CodeIt

Run the example, change one part, and use the result to check your understanding before moving to the next lesson.