Learning LibraryCore Coding LibraryTeens

try / except in Python: handle the errors you can predict

Someone types "twelve thousand" into your calculator. One malformed line sits in a file of a thousand orders. You can't prevent either, but you can decide what happens next.

The big idea

Code in a try block runs normally; if it raises the named exception, the except block runs instead of the program crashing.

See it in code

1The basics

float("lots") raises a ValueError. Wrapped in try, the error is caught and the program continues:

python
text = "lots"

try:
    launch_costs = float(text)
    print("Launch costs:", launch_costs)
except ValueError:
    print(f"'{text}' isn't a number. Enter digits only, like 12500.")
print("Program continues")
Run it. A conversion that fails, safely:
'lots' isn't a number. Enter digits only, like 12500.
Program continues

The line after the failed conversion was skipped, the except block ran, and execution carried on below. Without the try, the last line would never have printed.

2A step further

Combine try with a loop and a program can keep asking until it gets something usable:

python
import math

launch_costs = None
while launch_costs is None:
    try:
        launch_costs = float(input("Launch costs: "))
    except ValueError:
        print("That's not a number. Try again.")

print("Tees to break even:", math.ceil(launch_costs / 24))
Run it. A wrong answer, then a right one:
Launch costs: a lot
That's not a number. Try again.
Launch costs: 12500
Tees to break even: 521

The first answer raised ValueError, so launch_costs stayed None and the loop repeated. The second converted cleanly and the loop ended.

3At Evergreen

In a batch, one bad record shouldn't lose the rest. Catch the error per line, count the failures, and report them:

python
orders = ["TEE-SAGE-M,2,38.00", "PANTS-OAT-L,one,78.00", "TEE-CLAY-S,3,38.00", "SOCKS-NAVY-M,4,14.00"]

revenue = 0
skipped = 0
for order in orders:
    fields = order.split(",")
    try:
        revenue = revenue + int(fields[1]) * float(fields[2])
    except ValueError:
        skipped = skipped + 1
        print("Skipped a bad line:", order)

print(f"Batch revenue: ${revenue:.2f} ({skipped} line skipped)")
Run it. Four orders, one of them broken:
Skipped a bad line: PANTS-OAT-L,one,78.00
Batch revenue: $246.00 (1 line skipped)

The line with one for a quantity was reported and skipped; the other three were totaled. Counting the failures keeps the result honest about what it excludes.

The same idea, everywhere

The same structure guards anything outside your control: a file that may not exist, a network request that may fail, a dictionary key that may be missing.

Try it yourself

Add a second handler, except IndexError:, and test it with an order line that has only two fields. Then use except ValueError as error: and print error to see Python's own message.

The common mistake

Writing a bare except: that catches everything. It hides typos and real bugs along with the error you expected, and failures become invisible. Name the specific exception you're prepared for.

What it unlocks

To recognize which exception to catch, learn to read them in errors and debugging. Input handling begins with input(), and missing keys are a dictionary topic.