What are Python best practices for error handling and exception chaining?medium
Always catch specific exceptions, never bare except. Define custom exception hierarchies so callers can catch at different granularities. Use raise X from Y to chain exceptions and preserve the original traceback. raise X from None suppresses the original to present a clean error to callers.
Bare except: catches SystemExit and KeyboardInterrupt, masking serious problems. Custom exception hierarchies let you catch a broad base class for all domain errors or a specific subclass for a particular failure. The else block in try/except runs only when no exception was raised — better than putting success code at the end of try where it could be accidentally caught. The finally block always runs, even if a return is hit inside try. raise X from err sets __cause__ on the new exception and shows both in the traceback; raise X from None suppresses the original for clean external errors.