What are Python best practices for error handling and exception chaining?medium

Type
conceptual
Topic
error-handling
Frequency
common
Tags
exceptions, error handling, try/except, raise, custom exceptions
Answer

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.

Explanation

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.

Follow-upWhat is the difference between raise X from err and raise X from None?
Follow-upWhen would you use the else block in a try/except?
Follow-upWhy should you avoid bare except?