Definition
A mechanism used to manage runtime errors (exceptions) that occur during a program’s execution, preventing the program from crashing and allowing for graceful recovery.
Why It Matters
Systems must be resilient to the unpredictability of the real world, and exception handling is the mechanism that transitions code from “fragile” to “robust.” By explicitly planning for failures like missing files or bad input, you ensure that your software can “fail-forward” gracefully rather than crashing at the first sign of trouble.
Core Concepts
tryBlock: Contains the code that might raise an error.exceptBlock: If an error occurs, execution immediately jumps here.- The
raiseStatement: Used to manually trigger an exception:raise Exception('Error message'). This is used to signal that a function cannot proceed with the provided arguments or state. - Exceptions vs. Assertions:
- Exceptions are for expected errors (e.g., bad user input, missing files) that the program should handle gracefully.
- Assertions are for programmer errors (e.g., a “should never happen” state) and are used for debugging.
try:
with open('non_existent_file.txt') as f:
content = f.read()
except FileNotFoundError:
print("Sorry, the file does not exist.")
except Exception as e:
print(f"An unexpected error occurred: {e}")