Quick Answer
Manage errors gracefully with try-except blocks.
Understanding the Issue
Python uses try-except blocks to handle exceptions. The else clause runs when no exception occurs, while finally always executes. Be specific in catching exceptions to avoid masking bugs.
The Problem
This code demonstrates the issue:
Python
Error
# Risky operation that might fail
result = 100 / user_input
The Solution
Here's the corrected code:
Python
Fixed
try:
result = 100 / float(user_input)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid number")
else:
print("Result:", result)
finally:
print("Operation attempted")
Key Takeaways
Catch specific exceptions and clean up in finally.