GGistDev

Exception Handling in Python

Handle errors explicitly with try/except/else/finally. Raise exceptions to signal failure.

Basic try/except

Catch specific exceptions; order from most specific to most general.

try:
    risky()
except ValueError as e:
    handle(e)
except Exception as e:
    fallback(e)

else and finally

else runs when no exception occurs; finally always runs (cleanup).

try:
    result = compute()
except RuntimeError:
    recover()
else:
    use(result)
finally:
    cleanup()

Raising exceptions

Raise built‑ins or custom classes derived from Exception.

raise ValueError("bad input")

Custom exceptions

Create a clear hierarchy for domain errors.

class AppError(Exception):
    pass
class NotFound(AppError):
    pass

Exception chaining

Preserve context with raise ... from ....

try:
    parse()
except ValueError as e:
    raise RuntimeError("parse failed") from e

Context managers

Use with for automatic cleanup.

with open("file.txt") as f:
    data = f.read()

Best practices

  • Catch the narrowest exceptions possible
  • Prefer exceptions over sentinel return codes
  • Don’t suppress exceptions silently; log or re‑raise
  • Keep try blocks small; place only the statements that may raise

Summary

  • Use try/except/else/finally appropriately; model domain failures with custom exceptions
  • Chain exceptions for context; use context managers for resource safety