← Back to libraryQuestion 196 of 468
🐍PythonIntermediate

Exception Handling (try/except/else/finally)

📌 Definition:

Python handles errors with try/except blocks, optional else (runs if no exception) and finally (always runs). Catching specific exceptions makes tests fail clearly and clean up reliably.

📖 Detailed Explanation:

Code that might fail goes in try; matching exceptions are caught in except SpecificError as e. Catch the narrowest exception type (except ValueError, not bare except) so you don't hide bugs. else runs only when no exception occurred; finally always runs (cleanup like closing files/drivers). You raise errors with raise ValueError('msg'), and can define custom exceptions (class TestDataError(Exception)). In tests, prefer letting unexpected exceptions propagate (so the test fails loudly) and use try/except only where you genuinely handle or transform an error.

🔑 Key Points:
  • Catch specific exceptions, not bare except
  • else runs on success; finally always runs (cleanup)
  • raise for your own errors; subclass Exception for custom types
  • In tests, let unexpected errors propagate to fail loudly
🌍 Real-World Example:

Ensuring a WebDriver quits even if a step fails: try: run_steps() except AssertionError: capture_screenshot(); raise finally: driver.quit() — the browser always closes, and the failure still surfaces.

🎯 Scenario-Based Interview Question:

A teammate wraps a whole test in try/except: pass and it now 'passes' even when broken. Why is this dangerous?