QuickDevGuide

Home › Python

Exceptions — Python

Python follows EAFP — "easier to ask forgiveness than permission": try the operation and handle the exception, rather than checking every condition first. Full syntax Raising raise ValueError("message") raise AppError("context") from err — keeps the original as cause Re-raise the current exception with a bare raise. Custom exceptions Create a base class for your package (class AppError(Exception)) and specific subclasses. Callers can catch the whole family or just one. Common built-ins ValueError, TypeError, KeyError, IndexError, FileNotFoundError, ZeroDivisionError, AttributeError, TimeoutError. Never use a bare except: — it also catches KeyboardInterrupt and SystemExit. Catch Exception at most, and only at top-level boundaries.

Key Takeaways