This guide explains try, except, else, and finally through a focused Python example. You will learn the behavior to expect, why it matters in a real program, and how to recognize the common mistakes before applying it in your own project.
What You Will Learn
try/except/else/finally divides behavior into attempted work, recovery, successful completion and cleanup. else runs only if the try block succeeds; finally runs even when an error happens.
When and Why to Use It
The following example focuses on a practical use of try, except, else, and finally.
Step-by-Step Example
def parse_score(text):
try:
score = int(text)
except ValueError:
print("Invalid score")
return None
else:
print("Converted successfully")
return score
finally:
print("Parsing attempt finished")
parse_score("90")
Understanding the Example
For 90, the else message appears, then the finally message. The return value is 90, but finally still runs before the function returns.
Expected Output
Converted successfully
Parsing attempt finished
Important Behavior and Edge Cases
Avoid returning from finally; that can override a prior return or suppress an exception and conceal the original problem.
Try It Yourself
Call the function with invalid text and predict the order of its messages.
Common Beginner Mistakes
- Avoid returning from finally; that can override a prior return or suppress an exception and conceal the original problem.
- Handling the symptom rather than identifying the failing operation, or letting a broad exception handler hide defects.
- Skipping the practice step and assuming the example covers every input. Test at least one normal case and one edge case relevant to this topic.
Key Takeaways
- try/except/else/finally divides behavior into attempted work, recovery, successful completion and cleanup.
- For 90, the else message appears, then the finally message.
- Apply the technique deliberately, checking its documented input requirements and failure behavior before integrating it into a larger project.