12. Error & Exception Handling
Write resilient Python code: `try`, `except`, `else`, `finally`, `Built-in Exceptions`, `raising exceptions`, `custom exceptions`, `exception chaining`, and avoiding overly broad `except` blocks.
🎓 Junior Python Curriculum — Select Module
12. Python Error & Exception Handling Reference
1️⃣ Complete Exception Control Structure
val = int("42")
except ValueError as err:
print(f"Parsing error: {err}")
else:
print(f"Parsed integer successfully: {val}")
finally:
print("Completed parsing attempt.")
2️⃣ Built-in Exceptions Cheat Sheet
| Exception | Trigger Cause | Code Example |
|---|---|---|
| ZeroDivisionError | Division or modulo by zero. | 10 / 0 |
| ValueError | Valid type but inappropriate value. | int("abc") |
| TypeError | Incompatible operation on data types. | "5" + 5 |
| KeyError | Accessing missing dictionary key. | user_dict["missing"] |
| IndexError | Sequence index out of range bounds. | items[99] |
3️⃣ Custom Exceptions & Chaining (`from`)
Create custom domain-specific exception classes by inheriting from Exception or specialized exceptions like ValueError. Use raise NewError(...) from original_err for clean traceback chaining.
pass
try:
process_gateway_card()
except NetworkTimeout as err:
raise PaymentFailedError("Payment gateway failed") from err
4️⃣ Best Practices: Avoiding Overly Broad `except:`
- Never use bare
except:: Bare except catchesKeyboardInterruptandSystemExit, preventing user termination. - Catch specific exceptions: Always target exact exception types (`ZeroDivisionError`, `ValueError`).
- Write informative error messages: Include contextual information (e.g., variable values, user IDs) in exception messages.