Lab 09: Error Handling

🎯 Objective

Master Python's exception system — catching specific errors, raising custom exceptions, using finally for cleanup, and building robust fault-tolerant programs.

📚 Background

Errors are unavoidable in real programs: networks fail, files disappear, users type garbage. Exception handling lets your program respond gracefully instead of crashing. Python uses a rich exception hierarchy — BaseExceptionExceptionValueError, TypeError, etc. The try/except/else/finally structure gives you full control over error recovery.

⏱️ Estimated Time

30 minutes

📋 Prerequisites

  • Lab 8: File I/O

🛠️ Tools Used

  • Python 3.12

🔬 Lab Instructions

Step 1: Basic try/except

📸 Verified Output:

💡 Always catch the most specific exception possible. Catching Exception or (worse) BaseException hides bugs and makes debugging a nightmare.

Step 2: Multiple except Clauses

📸 Verified Output:

Step 3: else and finally Clauses

📸 Verified Output:

💡 else runs only when NO exception occurred — great for code that should run on success. finally runs ALWAYS — perfect for cleanup (closing files, releasing locks, etc.).

Step 4: Raising Exceptions

📸 Verified Output:

Step 5: Custom Exception Classes

📸 Verified Output:

Step 6: Exception Chaining

📸 Verified Output:

Step 7: Context Managers as Error Handlers

📸 Verified Output:

Step 8: Retry Pattern

📸 Verified Output:

✅ Verification

Expected output:

🚨 Common Mistakes

  1. Catching bare except:: Catches EVERYTHING including KeyboardInterrupt and SystemExit — always specify exception type.

  2. Silently swallowing exceptions: except: pass hides bugs — at minimum log the error.

  3. Too broad catch: except Exception: is often too wide — catch the specific type you expect.

  4. Not using finally: Resources (files, connections) leak if you forget to close them on error.

  5. Raising strings: raise "error message" is a TypeError — always raise ExceptionClass("message").

📝 Summary

  • try/except/else/finally — full exception handling structure

  • Catch specific exceptions, not bare except:

  • else runs on success only; finally runs always (use for cleanup)

  • raise ExceptionType("message") to signal errors; raise ... from e for chaining

  • Custom exceptions: inherit from Exception for domain-specific error types

  • Retry patterns handle transient failures (network, I/O)

🔗 Further Reading

Last updated