Exception Handling
Try-Except Blocks
Fundamental exception handling with try/except
Interview: Essential — tests understanding of Python error handling, exception hierarchy, and EAFP philosophy
Exception handling with try/except is the foundation of robust Python programs. Python follows the EAFP (Easier to Ask Forgiveness than Permission) philosophy — try the operation and handle failures rather than checking conditions first. This leads to cleaner, more Pythonic code.
Exception Hierarchy
BaseException→ root of all exceptionsException→ all regular exceptions (catch this, not BaseException)ValueError,TypeError,KeyError,IndexError→ common built-in exceptionsSystemExit,KeyboardInterrupt→ inherit from BaseException, not Exception
Best Practices
- Catch specific exceptions, not bare
except: - Use
except Exception as eonly as a last resort - Never catch
BaseException(would catch Ctrl+C, SystemExit) - Keep try blocks small — only wrap the code that might raise
Interview Tip
Know the difference between EAFP (try/except) and LBYL (if/else checks). Python prefers EAFP because it avoids race conditions and is more readable.
Use Cases
Handling user input validation and parsing errors
File operations (missing files, permission errors)
Network requests (timeouts, connection failures)
API calls (JSON decode errors, missing keys)
Graceful degradation in production systems
Common Mistakes
Using bare except: — catches SystemExit, KeyboardInterrupt too
Catching Exception too broadly — hides bugs instead of fixing them
Making try blocks too large — only wrap code that might raise
Not logging exceptions — errors are silently swallowed
Catching BaseException — would prevent Ctrl+C from working