Python Standard Library — 17. Built in exception


Previous article: Python Standard Library — 16. Built in type: context manager type, other, special attribute
Next article: Python Standard Library — 18. Text processing service: String common string operations

In Python, all exceptions must be instances of a class derived from baseexception In a try statement with an exception clause that refers to a specific class, the clause also handles any exception classes derived from that class (but not the exception classes it derives from) Two unrelated exception classes created by subclassing are never equivalent, even if they have the same name.

The built-in exceptions listed below can be generated by an interpreter or built-in function. Unless otherwise specified, they all have an associated value that prompts for the detailed cause of the error This can be a string or a tuple of multiple information items, such as an error code and an interpreted error string The associated value is usually passed as a parameter to the constructor of the exception class.

User code can throw built-in exceptions This can be used to test exception handlers or report error conditions “as if” the same exception had been raised by the interpreter; note, however, that there is no mechanism to prevent user code from raising inappropriate errors.

Built in exception classes can be subclassed to define new exceptions; programmers are encouraged to derive new exceptions from the exception class or one of its subclasses instead of baseexception More information about defining exceptions can be found in the user defined Exceptions section of the python tutorial.

When an exception is raised (or re raised) in the exception or finally clause, the “context” will be automatically set as the last exception caught; if the new exception is not handled, the final backtracking information displayed will include the original exception and the last exception.

When a new exception is thrown (instead of simply using raise to re throw the currently handled exception), the implicit exception context can supplement an explicit reason by using from with raise:

raise new_exc from original_exc

The expression following from must be an exception or none It will be set toCause__. Set causeAnd implicitlysuppress_contextProperty is set to true, so that using raise new ﹣ exc from none can effectively replace the old exception with the new one to show its purpose (for example, converting keyerror to attributeerror), while letting the old exceptioncontextIs available for introspection during debugging.

In addition to the backtracking of the exception itself, the default backtracking also shows these concatenated exceptions.causeThe explicit concatenation exception in is always displayed if it exists.contextThe implicit concatenation exception incauseFor none andsuppress_contextDisplayed when it is a false value.

In either case, the exception itself is always displayed after any concatenated exception, so that the last row of the backtrace always shows the last exception thrown.

Base class

The following exceptions are mainly used as base classes for other exceptions.

exception BaseException

Base class for all built-in exceptions It should not be inherited directly by user-defined classes (use exception in this case) If str() is called on an instance of this class, the parameter representation of the instance is returned, or an empty string is returned when there are no parameters.


A tuple of parameters passed to the exception constructor Some built-in exceptions (such as oserror) accept a specific number of parameters and give special meaning to the elements in this tuple, while others usually accept only a single string giving error information.


This method sets TB as the new backtracking information of the exception and returns the exception object It is usually used in exception handlers in the following form:
        except SomeException:
            tb = sys.exc_info()[2]
            raise OtherException(...).with_traceback(tb)

exception Exception

All built-in non system exit class exceptions derive from this class All user-defined exceptions should also derive from this class.

exception ArithmeticError

This base class is used to derive built-in exceptions raised for various arithmetic errors: overflow error, zerodivisionerror, floatingpointerror.

exception BufferError

Raised when a buffer related operation cannot be performed.

exception LookupError

This base class is used to derive exceptions that are thrown when a key or index used by a map or sequence is invalid: indexerror, keyerror This can be raised directly through codecs. Lookup().

Specific anomaly

The following exceptions are frequently thrown.

exception AssertionError

Is raised when the assert statement fails.

exception AttributeError

Raised when a property reference (see property reference) or assignment fails (typeerror is raised when an object does not support property references or property assignments at all.)

exception EOFError

Is raised when the input() function reaches the end of file condition (EOF) without reading any data (in addition, the IO. Iobase. Read() and Io. Iobase. Readline() methods will return an empty string when encountering EOF.)

exception FloatingPointError

Currently not used.

exception GeneratorExit

Raised when a generator or coroutine is closed; see generator. Close() and coroutine. Close() It inherits directly from baseexception rather than exception, because technically it is not an error.

exception ImportError

Raised when an import statement encounters trouble trying to load a module It is also raised when there is a name that cannot be found in "from list" in from... Import.

The name and path attributes can be set by using a keyword only parameter on the constructor After setting, they will respectively represent the name of the module to be imported and the path of any file that triggers the exception.

Changed in version 3.3: name and path attributes added.

exception ModuleNotFoundError

Subclass of importerror, raised by import when a module cannot be located It is also raised when none is found in sys.modules.

3.6 new functions

exception IndexError

Raised when sequence extraction is out of range (the slice index is silently truncated to the allowed range; typeerror is raised if the specified index is not an integer.)

exception KeyError

Raised when the specified mapping (Dictionary) key cannot be found in an existing key collection.

exception KeyboardInterrupt

Raised when the user presses the interrupt key (usually Control-C or delete) During execution, interrupt signals are detected periodically This exception inherits from baseexception to ensure that it is not accidentally caught by the code handling the exception, which avoids exiting the interpreter.

exception MemoryError

Raised when an operation runs out of memory but the condition can still be saved (by deleting some objects) The associated value is a string indicating which (internal) operation ran out of memory Please note that due to the underlying memory management architecture (malloc() function of C), the interpreter may not always be able to fully recover from this situation; however, after all, it can cause an exception, so that stack backtracking information can be printed out, so as to find out the out of control procedure that causes the problem.

exception NameError

Raised when a local or global name is not found This exception is for unqualified names only The associated value is an error message with a name that was not found.

exception NotImplementedError

This exception derives from runtimeerror In a user-defined base class, an abstract method should overload the method when it requires a derived class, or raise this exception when the class it requires to develop prompts that the concrete implementation needs to be added.


It should not be used to indicate that an operator or method is not supported at all — in this case, leave the specific operator / method undefined, or set it to none in the subclass.


Not implemented error and not implemented are not interchangeable, even if they have similar names and uses See not implemented for detailed instructions on when to use them.

exception OSError([arg])

exception OSError(errno, strerror[, filename[, winerror[, filename2]]])

This exception will be thrown when a system function returns a system related error, such as I / O operation failure such as "file not found" or "disk full" (excluding illegal parameter type or other accidental errors).

The second form of the constructor can set the corresponding properties as described below If these properties are not specified, the default is none For downward compatibility, if three parameters are passed in, the args attribute will contain only two tuples of the first two constructor parameters.

Constructors actually return a subclass of oserror, as described in OS exceptions below The specific subclass depends on the final errno value This behavior occurs only when an oserror is constructed directly or through an alias, and is not inherited when subclassed.


The numeric error code from the C variable errno.


Under windows, this parameter will give the native windows error code The errno attribute will be the approximate conversion form of the native error code in POSIX platform.

    Under windows, if the winerror constructor parameter is an integer, the errno attribute is determined by the windows error code, and the errno parameter is ignored On other platforms, the winerror parameter is ignored and the winerror property does not exist.


The corresponding error information provided by the operating system It is formatted by C function perror() in POSIX platform, and formatmessage() in windows.

### filename
### filename2

For exceptions related to file system paths, such as open() or OS. Unlink(), filename is the filename passed to the function For functions involving two file system paths (for example, OS. Rename()), filename2 will be the second filename passed to the function.

Changes in version 3.3: environmenterror, ioerror, windowserror, socket.error, select.error and mmap.error have been merged into oserror, and the constructor may return one of the subclasses.

Changed in version 3.4: the filename attribute will now be the original filename passed to the function, not the name encoded or decoded based on the file system encoding In addition, filename2 constructor parameters and properties are added.

exception OverflowError

Raised when the result of an arithmetic operation is too large to be represented This is not possible for integers (it is better to raise a memoryerror than to give up the attempt) However, for historical reasons, overflow error is sometimes raised when the integer is out of the required range Because of the lack of standardization of floating-point exception handling in C, most floating-point operations will not be checked.

exception RecursionError

This exception derives from runtimeerror It is raised when the interpreter detects that the maximum recursion depth is exceeded (see sys. Getrecursionlimit()).

New 3.5 features: only runtimeerror will be raised before this.

exception ReferenceError

This exception will be thrown when a weak reference created using the weakref. Proxy() function is used to access a property of the reference that has been garbage collected For more information about weak references, see the weakref module.

exception RuntimeError

Raised when an error that does not belong to any other category is detected The associated value is a string that indicates what the problem is.

exception StopIteration

Raised by the  next  method of the built-in functions next() and iterator to indicate that the iterator cannot produce the next item.

The exception object has only one attribute value, which is given as a parameter when constructing the exception. The default value is none.

When a generator or coroutine function returns, a new stopiteration instance is raised, and the value returned by the function is used as the value parameter of the exception constructor.

If a generator code raises stopiteration directly or indirectly, it is converted to a runtime error (and keeps stopiteration as the cause of the new exception).

Change in version 3.3: added value attribute and its function used as return value by generator function.

Change in version 3.5: the runtime error conversion is implemented through "from" future "import generator" stop, see PEP 479.

Change in version 3.7: PEP 479 is enabled by default for all code: stopiteration errors raised in the generator will be converted to runtimeerrors.

exception StopAsyncIteration

Must be raised by the 'next' method of an asynchronous iterator object to stop the iteration.

3.5 new functions

exception SyntaxError

Is raised when the parser encounters a syntax error This can happen when an import statement, a call to the built-in function exec() or eval(), or reading the original script or standard input (including interaction mode).

The instance of this class contains the attributes filename, lineno, offset and text for convenient access to the corresponding details Str() of the exception instance returns only the message text.

exception IndentationError

Base class with syntax errors associated with incorrect indentation This is a subclass of syntaxerror.

exception TabError

Raised when indentation contains inconsistent use of tab and space characters This is a subclass of indexationerror.

exception SystemError

Raised when the interpreter finds an internal error, but it does not appear to be serious enough to give up all hope The associated value is a string (represented as a low-level symbol) indicating what went wrong.

You should report this problem to the author or maintainer of your Python interpreter Please confirm the version number (sys. Version; it will also be printed at the beginning of the interactive Python session), the specific error message (the value associated with the exception), and the source code of the program that may trigger the error.

exception SystemExit

This exception is thrown by the sys. Exit() function It inherits from baseexception rather than exception to ensure that it is not accidentally caught by the code handling the exception This allows the exception to properly propagate up and cause the interpreter to exit If it is not processed, the Python interpreter exits; no stack backtracking information is printed The constructor accepts the same optional parameters as passed to sys. Exit() If the value is an integer, it indicates the system exit status code (which is passed to the exit() function of C); if the value is none, the exit status code is zero; if the value is of another type (such as string), the value of the object is printed and the exit status code is set to one.

The call to sys. Exit() is converted to an exception so that the cleanup handler (the finally clause of the try statement) can be executed, and the debugger can execute a script without running out of control If you absolutely need to exit immediately (for example, in a child process after calling OS. Fork()), you can use OS. 


Exit status code or error message passed to the constructor (default is none.)

exception TypeError

Raised when an operation or function is applied to an object of an inappropriate type The associated value is a string giving details about the type mismatch.

This exception can be raised by user code to indicate that the operation attempted on an object is not supported or should not be supported If an object should support the given operation but has not yet provided an implementation, the appropriate exception to throw should be notimplementederror.

The type error of the passed in parameter (for example, when an int is required but a list is passed in) should result in a typeerror, but the value error of the passed in parameter (for example, a value outside the scope of the request) should result in a valueerror.

exception UnboundLocalError

Raised when a local variable is referenced in a function or method, but it is not bound to any value This exception is a subclass of NameError.

exception UnicodeError

Raised when a Unicode related encoding or decoding error occurs This exception is a subclass of valueerror.

Unicode error has properties that describe encoding or decoding errors For example, err.object [err. Start: err. End] will give specific invalid input that causes the codec to fail.


The encoding name that caused the error.


A string describing the specific codec error.


The object the codec is trying to encode or decode.


The starting index of invalid data in the object.


End position index of invalid data in object (not included).

exception UnicodeEncodeError

Raised when a Unicode related error occurs during encoding This exception is a subclass of Unicode error.

exception UnicodeDecodeError

Raised when a Unicode related error occurs during decoding This exception is a subclass of Unicode error.

exception UnicodeTranslateError

Raised when a Unicode related error occurs during a transcribe This exception is a subclass of Unicode error.

exception ValueError

Is thrown when an operation or function receives an argument of the correct type but with an unsuitable value, and the condition cannot be described with a more precise exception such as indexerror.

exception ZeroDivisionError

Raised when the second parameter of a division or remainder operation is zero The associated value is a string indicating the operand and the type of operation.

The following exceptions are reserved for compatibility with previous versions; starting with Python 3.3, they are all aliases for oserror.

exception EnvironmentError

exception IOError

exception WindowsError

Limited to windows.

OS anomaly

The following exceptions are subclasses of oserror and will be thrown based on the system error code.

exception BlockingIOError

Raised when an operation is blocked by an object set as a non blocking operation, such as a socket Corresponding to errno eagain, ealready, ewouldblock and einprogress.

In addition to the existing properties of oserror, blockingioerror has an additional property:
  • characters_written

An integer representing the number of characters written to the stream before being blocked This property is available when using buffered I / O classes from Io modules.

exception ChildProcessError

Raised when an operation on a subprocess fails Corresponds to errno echild.

exception ConnectionError

Base class for connection related problems.

Its subclasses are brokenpipeerror, connectionabortederror, connectionreusederror and connectionreseterror.

exception BrokenPipeError

A subclass of connectionerror that is raised when an attempt is made to write to a pipe that has been closed at the other end, or to write to a socket that has been closed for writing Corresponds to errno epipe and eshutdown.

exception ConnectionAbortedError

Subclass of connectionerror, which is raised when a connection attempt is aborted by the peer Corresponds to errno econnaborted.

exception ConnectionRefusedError

Subclass of connectionerror, which is raised when a connection attempt is rejected by the peer Corresponds to errno econnreused.

exception ConnectionResetError

Subclass of connectionerror, which is raised when the connection is reset end-to-end Corresponds to errno econnreset.

exception FileExistsError

Raised when an attempt is made to create an existing file or directory Corresponds to errno eexist.

exception FileNotFoundError

Raised when the requested file or directory does not exist Corresponds to errno enoent.

exception InterruptedError

Raised when a system call is interrupted by an input signal Corresponds to errno Eintr.

Change in version 3.5: when a system call is interrupted by a signal, python will now retry the system call unless the signal's handler raises other exceptions (see PEP 475 for principle) instead of interruptederror.

exception IsADirectoryError

When a request to perform a file operation on a directory, such as OS. Remove(), is raised Corresponding to errno eisdir.

exception NotADirectoryError

Is raised when a request is made to perform a directory operation on a non directory object, such as OS. Listdir() Corresponds to errno enotdir.

exception PermissionError

Is raised when an attempt is made to perform an operation without sufficient operating privileges - for example, missing file system privileges Corresponding to errno eacces and eperm.

exception ProcessLookupError

Raised when the given process does not exist Corresponds to errno esrch.

exception TimeoutError

Raised when a system level timeout occurs for a system function Corresponds to errno etimedout.

3.3 new function: all the above subclasses of oserror are added.

See also

Pep 3151 – override the hierarchy of OS and IO exceptions


The following exceptions are used as warning categories; see the warning categories documentation for details.

exception Warning

The base class for the warning category.

exception UserWarning

Base class for warnings generated by user code.

exception DeprecationWarning

This is the base class for warnings related to deprecated features if the warnings are directed at other Python developers.

exception PendingDeprecationWarning

Base classes for feature related warnings that are obsolete and are expected to be deprecated in the future, but are not currently deprecated.

This class is rarely used because it is not common to warn against possible future retirements, while deprecationwarning is recommended for existing retirements.

exception SyntaxWarning

The base class for warnings related to fuzzy syntax.

exception RuntimeWarning

The base class for warnings related to fuzzy runtime behavior.

exception FutureWarning

This is the base class for warnings related to deprecated features if the warnings are issued for end users of applications written in Python.

exception ImportWarning

Base class for warnings related to possible errors in module import.

exception UnicodeWarning

Base class for Unicode related warnings.

exception BytesWarning

Base class for warnings related to bytes and byte array.

exception ResourceWarning

Base class for warnings related to resource usage Is ignored by the default warning filter.

3.2 new functions

Exception hierarchy

The class hierarchy of built-in exceptions is as follows:

Python Standard Library -- 17. Built in exception

Previous article: Python Standard Library — 16. Built in type: context manager type, other, special attribute
Next article: Python Standard Library — 18. Text processing service: String common string operations