The try and except Blocks
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)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)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.