Exceptions
Handle expected failures precisely while keeping unexpected failures visible.
On this page
The concept
An exception changes normal control flow. Place the smallest appropriate risky operation in try, and catch the specific exception you can handle. else runs when the try suite succeeds. finally runs when leaving the construct through ordinary completion or exception propagation, which supports cleanup.
A traceback shows the call chain and failing location. Start at its final line to identify the exception type and message, then locate the relevant file and line. A SyntaxError must be fixed before that file can execute; it is not the same as invalid user data discovered at runtime.
Worked example
for raw_number in ["5", "0", "hello"]:
try:
number = int(raw_number)
result = 10 / number
except ValueError:
print("Please enter a number:", raw_number)
except ZeroDivisionError:
print("Division by zero is not allowed.")
else:
print("Result:", result)
finally:
print("Attempt finished.")Trace the result
- The string "5" parses and divides successfully.
- The string "0" parses but triggers ZeroDivisionError; "hello" triggers ValueError earlier.
- The final message appears for each attempt, while the result message appears only for a successful attempt.
Result: 2.0
Attempt finished.
Division by zero is not allowed.
Attempt finished.
Please enter a number: hello
Attempt finished.Line-by-line walkthrough
Lines 1–12: for raw_number in ["5", "0", "hello"]:
Obtain each item from ['5', '0', 'hello'] and bind it to raw_number before executing the body. A tuple-shaped target unpacks that item. A loop else, if present, runs only when completion does not use break.
Lines 2–12: try:
Run the protected body. A matching except handles its specified failure. An else suite runs after a successful try body, and finally runs when leaving the construct. This structure should handle expected failures without concealing unrelated bugs.
Line 3: number = int(raw_number)
Evaluate int(raw_number), then bind or update number with the result. The call finishes before its return value is bound; a failed call does not produce a successful assignment. Assignment itself does not imply a deep copy.
Line 4: result = 10 / number
Evaluate 10 / number, then bind or update result with the result. Assignment itself does not imply a deep copy.
Alternative or completion suite: read the statements below as part of this branch.
Line 10: print("Result:", result)
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Cleanup suite: read the statements below as part of this branch.
Line 12: print("Attempt finished.")
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Handler for ValueError: control reaches this suite only for a matching exception from the protected body.
Line 6: print("Please enter a number:", raw_number)
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Handler for ZeroDivisionError: control reaches this suite only for a matching exception from the protected body.
Line 8: print("Division by zero is not allowed.")
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Common mistake
A bare except or except: pass can hide programming errors. Catch only the failure you understand and have a useful response for.