Python Programming from First Principles: Learn to Code, Think Computationally, and Solve Real-World Problems
PDFEPUB
BOOK 000 · CHAPTER 6 · The`try` and`except` Blocks

The try and except Blocks

On this pageHandle an expected failureDistinguish different errorsCleanup with finally

An expression can be valid Python and still fail when it runs. Converting unsuitable text raises ValueError; dividing by zero raises ZeroDivisionError.

Handle an expected failure

Put the operation that may fail in try. An except block handles the named exception. Other exceptions continue to the caller.

answer = "not a number"
try:
    value = float(answer)
except ValueError:
    print("Enter a number.")
else:
    print(value)
Listing 269 — Handle an expected failure

Output

Enter a number.

Change answer to "12.5". Predict which block runs, then rerun the cell. else runs when the try block completes without an exception.

Distinguish different errors

numerator = "12"
denominator = "0"
try:
    result = float(numerator) / float(denominator)
except ValueError:
    print("Both values must be numbers.")
except ZeroDivisionError:
    print("The divisor must not be zero.")
else:
    print(result)
Listing 270 — Distinguish different errors

Output

The divisor must not be zero.

Use denominator "4", then "zero", then "0". Predict the result each time. Catch the error you can explain and handle; a broad handler can hide an unrelated programming mistake.

Cleanup with finally

A finally block runs when control leaves the try statement, including after an exception. Use it for cleanup. For files, a with statement usually expresses resource cleanup more clearly; the file-handling chapter develops that pattern.

Reference: Python: Errors and Exceptions, checked 20 October 2026.