Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 06 / Topic 4 of 10

try / except

Put the risky line in try. Put the "what to do if it fails" code in except. It is like a safety net under a tightrope walker: if they fall, the net catches them and the show goes on. Always name the specific exception you expect. as e stores the exception in e; print(e) shows its message.

Real-world example: convert the quantity typed in an order form.

text = "two"
try:
    qty = int(text)
except ValueError as e:
    print("Please type a number.")
    print("Details:", e)
    qty = 1
print("Quantity:", qty)
Please type a number.
Details: invalid literal for int() with base 10: 'two'
Quantity: 1

Many except blocks

Python checks them top to bottom and runs the first one that matches.

prices = {"tea": 15, "coffee": 25}

def price_per_person(item, people):
    try:
        return prices[item] / people
    except KeyError:
        return f"'{item}' is not on the menu"
    except ZeroDivisionError:
        return "People must be more than 0"

print(price_per_person("tea", 3))      # 5.0
print(price_per_person("juice", 3))    # 'juice' is not on the menu
print(price_per_person("coffee", 0))   # People must be more than 0

You can also catch two types in one block: except (ValueError, TypeError):.

๐Ÿ” Going deeper: order matters. Put specific exceptions before general ones: if except LookupError: came first, the KeyError block below it would never run. After an except block ends, Python deletes e, so do not use it later.

Read more: the official tutorial's errors and exceptions chapter.

Done here? The practice set for Part 6 โ€” 7 exercises with solutions โ€” is on the part page.

Search the guide