18.Errors & Exceptions in Python
What is an Exception?
An exception is a runtime event that interrupts normal control flow. When raised, Python searches for the nearest matching except block up the call stack. If none is found, the program terminates and prints a traceback showing where and why it failed.
def divide(a, b):
return a / b # Raises ZeroDivisionError when b == 0
print(divide(10, 0))
Output (simplified):
Traceback (most recent call last):
File “…”, line 4, in <module>
print(divide(10, 0))
File “…”, line 2, in divide
return a / b
ZeroDivisionError: division by zero
2. The try / except / else / finally Blocks
Python’s error-handling uses four clauses: try, except, else, finally. Guidelines: keep try blocks small, use else for post-success logic, and finally for cleanup.
3 .Catching Exceptions Properly
Catch specific exceptions, avoid bare except. Use multiple exception tuples and re-raise after logging or cleanup.
4. Raising Exceptions
Use raise to signal error conditions. Choose built-in types when applicable. Create custom exceptions for libraries/APIs.
5 .Exception Hierarchy (Quick Mental Model)
All standard exceptions inherit from BaseException. Catch subclasses of Exception, not BaseException.
7.EAFP vs LBYL
EAFP: Easier to Ask Forgiveness than Permission; LBYL: Look Before You Leap. Prefer EAFP for I/O and concurrency hazards.
8.Exception Chaining and Context
Use raise X from e to preserve context when handling one exception leads to another.
9.assert Statements (for Internal Invariants)
Use assert for developer checks, not user input validation. Assertions can be disabled with -O flag.
10 Warnings vs Exceptions
Use warnings module for non-fatal issues like deprecations.