Exception Handling
Overview
Exception handling lets you catch and manage runtime errors safely so your program doesn't crash.
Learning Objectives
- Catch specific errors using try, except, else, and finally.
- Create and raise custom exceptions.
- Clean up resources safely inside finally blocks.
Concept Explanation
When Python encounters an error at runtime, it raises an exception. You can catch these exceptions using try and except blocks. The else block runs only if no errors were raised, and the finally block executes unconditionally to clean up resources.
Code Examples
Example 1 — Basics
This example introduces the fundamental syntax and concepts.
try:
x = 10 / 0
except ZeroDivisionError:
print('You cannot divide by zero!')
Example 2 — Everyday Usage
This example demonstrates a realistic scenario handling business parameters.
def lookup_score(scores_dict, student_name):
try:
return scores_dict[student_name]
except KeyError:
print(f'Student {student_name} not found.')
return 0
finally:
print('Lookup completed.')
Example 3 — Advanced Example
This example shows clean, production-grade code structure following senior development standards.
# Define custom exceptions class safely
class InsufficientBalanceError(Exception): pass
class Account:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
if amount > self.balance:
raise InsufficientBalanceError(f'Cannot withdraw {amount}')
self.balance -= amount
return self.balance
acc = Account(50)
try:
acc.withdraw(100)
except InsufficientBalanceError as e:
print(f'Transaction blocked: {e}')
Visual Flow
The following execution flow represents the step-by-step evaluation inside the interpreter:
Run try block code → Error raised? → Match except statement → Run block → Run finally cleanup
Common Mistakes
Review these common pitfalls when working with this topic:
- Using a bare except: statement, which catches critical system signals like exit requests.
- Hiding execution bugs by catching generic exceptions silently without logging them.
- Forgetting that finally blocks run even if return statements are executed inside try blocks.
- Raising generic Exception instances instead of defining topic-specific exception classes.
Best Practices
Enforce these Pythonic best practices in your codebase:
try:
val = data[k]
except:
val = None # Bare except blocks hide actual code bugs
try:
val = data[k]
except KeyError:
val = None # Catch only targeted exceptions
Quick Revision
Use these key summaries for last-minute revision:
- try wraps code blocks that might raise errors.
- except handles specific exception classes.
- else executes only if no exceptions occur.
- finally always executes to clean up resources.
- raise triggers exceptions manually.
- Custom exceptions inherit from Exception.