Errors and debugging
Handle expected errors
Use try, except, else, and finally for failures you can handle.
Lesson 35 of 63
Reading: about 2 min
Lesson + practice: about 15 min
Difficulty: Beginner
On this page4 sections
Place an operation that may fail inside try. An except block handles a named exception. Use a narrow exception type so unrelated failures are not hidden. else runs only when try succeeds; finally runs whether it succeeds or fails.
responses = ["25", "not a number"]
for response in responses:
try:
minutes = int(response)
except ValueError:
print("Enter a whole number")
else:
print(f"Saved {minutes} min")
finally:
print("Attempt finished")Saved 25 min Attempt finished Enter a whole number Attempt finished
Do not hide every exception
Avoid a bare except: block in ordinary lesson code. It can swallow mistakes you did not intend to handle. Catch ValueError when converting text with int(), and let unrelated errors surface for debugging.
Why this works
Only statements inside try are watched by its except clauses. If int(response) raises ValueError, Python skips the rest of try and enters the matching except. If conversion succeeds, else runs. finally then runs in both cases, which is useful for cleanup or a completion message.
Practice
Write a function that converts a text response to int. Return the number on success and None for ValueError, then call it with "12" and "twelve".
When does else run in a try statement?
Reveal answer
Only when the try block finishes without raising an exception.
Try another case
If response is "bad", do else and finally run in the lesson example?
Check your answer
Reveal answer
else does not run because conversion raised ValueError. finally still runs.
Your progress
Reveal the check answer or reach the end to complete this lesson.