61 8.5. Exception Chaining (continues on next page) Python Tutorial, Release 3.9.5 The raise statement allows an optional from which enables chaining exceptions. For example: This can be useful when you are transforming exceptions. For example: Exception chaining happens automatically when an exception is raised inside an $_{except}$or finally section. Exception chaining can be disabled by using$_{from None}$ idiom: For more information about chaining mechanics, see bltin-exceptions. Programs may name their own exceptions by creating a new exception class (see Classes for more about Python classes). Exceptions should typically be derived from the$_{Exception}$class, either directly or indirectly. Exception classes can be defined which do anything any other class can do, but are usually kept simple, often only offering a number of attributes that allow information about the error to be extracted by handlers for the exception. When creating a module that can raise several distinct errors, a common practice is to create a base class for exceptions defined by that module, and subclass that to create specific exception classes for different error conditions: 8.6 User-defined Exceptions classError (Exception): """Base class for exceptions in this module.""" pass classInputError (Error): """Exception raised for errors in the input. >>> try : ... open('database.sqlite ') ... except OSError: ... raise RuntimeError from None ... Traceback (most recent call last): File "<stdin>" , line4, in <module> RuntimeError >>> def func(): ... raise IOError ... >>> try : ... func() ... except IOError as exc: ... raise RuntimeError('Failed to open database') from exc ... Traceback (most recent call last): File "<stdin>" , line2, in <module> File "<stdin>" , line2, in func OSError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<stdin>" , line4, in <module> RuntimeError: Failed to open database # exc must be exception instance or None. raise RuntimeError from exc 8.5 Exception Chaining