๐Ÿ  VisualStudioTutor.com  ยท  Python Tutorial Home  ยท  Python Lesson 8 of 40
Lesson 8 of 40 Foundations Beginner โฑ 25 min

Exception Handling & Context Managers

Handle errors gracefully with try/except/else/finally, custom exceptions, and create your own context managers with contextlib.

Part 1: try / except / else / finally

try:
    result = int(user_input) / int(divisor)
except ValueError:
    print("Please enter a valid number")
except ZeroDivisionError:
    print("Cannot divide by zero")
except (TypeError, OverflowError) as e:
    print(f"Error: {e}")
else:
    print(f"Result: {result}") # runs only if no exception
finally:
    print("Always runs")

Part 2: Custom Exceptions

class AppError(Exception):
    """Base exception for our app."""

class ValidationError(AppError):
    def __init__(self, field: str, message: str):
        self.field = field
        super().__init__(f"Validation failed on '{field}': {message}")

raise ValidationError("email", "Invalid format")

Part 3: Context Managers with contextlib

from contextlib import contextmanager, suppress

@contextmanager
def timer(label: str = "Task"):
    import time
    start = time.perf_counter()
    yield
    elapsed = time.perf_counter() - start
    print(f"{label}: {elapsed:.3f}s")

with timer("Data processing"):
    process_large_dataset()

# Suppress specific exceptions
with suppress(FileNotFoundError):
    Path("optional.txt").unlink()

Part 4: Exception Chaining & Notes

try:
    load_config()
except FileNotFoundError as e:
    # raise ... from preserves original
    raise RuntimeError("Config failed to load") from e

# Python 3.11+ exception notes
try:
    risky_operation()
except ValueError as e:
    e.add_note(f"Failed for user {user_id}")
    raise
๐Ÿ“˜ Want the complete guide with projects? Get the book โ†’