Built-in Exceptions

In Python, all exceptions must be instances of a class that derives fromBaseException. In atry statement with anexceptclause that mentions a particular class, that clause also handles any exceptionclasses derived from that class (but not exception classes from whichit isderived). Two exception classes that are not related via subclassing are neverequivalent, even if they have the same name.

The built-in exceptions listed below can be generated by the interpreter orbuilt-in functions. Except where mentioned, they have an “associated value”indicating the detailed cause of the error. This may be a string or a tuple ofseveral items of information (e.g., an error code and a string explaining thecode). The associated value is usually passed as arguments to the exceptionclass’s constructor.

User code can raise built-in exceptions. This can be used to test an exceptionhandler or to report an error condition “just like” the situation in which theinterpreter raises the same exception; but beware that there is nothing toprevent user code from raising an inappropriate error.

The built-in exception classes can be subclassed to define new exceptions;programmers are encouraged to derive new exceptions from theExceptionclass or one of its subclasses, and not fromBaseException. Moreinformation on defining exceptions is available in the Python Tutorial underUser-defined Exceptions.

When raising (or re-raising) an exception in anexcept orfinally clause__context__ is automatically set to the last exception caught; if thenew exception is not handled the traceback that is eventually displayed willinclude the originating exception(s) and the final exception.

When raising a new exception (rather than using a bareraise to re-raisethe exception currently being handled), the implicit exception context can besupplemented with an explicit cause by usingfrom withraise:

raisenew_excfromoriginal_exc

The expression followingfrom must be an exception orNone. Itwill be set as__cause__ on the raised exception. Setting__cause__ also implicitly sets the__suppress_context__attribute toTrue, so that usingraisenew_excfromNoneeffectively replaces the old exception with the new one for displaypurposes (e.g. convertingKeyError toAttributeError), whileleaving the old exception available in__context__ for introspectionwhen debugging.

The default traceback display code shows these chained exceptions inaddition to the traceback for the exception itself. An explicitly chainedexception in__cause__ is always shown when present. An implicitlychained exception in__context__ is shown only if__cause__isNone and__suppress_context__ is false.

In either case, the exception itself is always shown after any chainedexceptions so that the final line of the traceback always shows the lastexception that was raised.

Base classes

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

exceptionBaseException

The base class for all built-in exceptions. It is not meant to be directlyinherited by user-defined classes (for that, useException). Ifstr() is called on an instance of this class, the representation ofthe argument(s) to the instance are returned, or the empty string whenthere were no arguments.

args

The tuple of arguments given to the exception constructor. Some built-inexceptions (likeOSError) expect a certain number of arguments andassign a special meaning to the elements of this tuple, while others areusually called only with a single string giving an error message.

with_traceback(tb)

This method setstb as the new traceback for the exception and returnsthe exception object. It is usually used in exception handling code likethis:

try:...exceptSomeException:tb=sys.exc_info()[2]raiseOtherException(...).with_traceback(tb)
exceptionException

All built-in, non-system-exiting exceptions are derived from this class. Alluser-defined exceptions should also be derived from this class.

exceptionArithmeticError

The base class for those built-in exceptions that are raised for variousarithmetic errors:OverflowError,ZeroDivisionError,FloatingPointError.

exceptionBufferError

Raised when abuffer related operation cannot beperformed.

exceptionLookupError

The base class for the exceptions that are raised when a key or index used ona mapping or sequence is invalid:IndexError,KeyError. Thiscan be raised directly bycodecs.lookup().

Concrete exceptions

The following exceptions are the exceptions that are usually raised.

exceptionAssertionError

Raised when anassert statement fails.

exceptionAttributeError

Raised when an attribute reference (seeAttribute references) orassignment fails. (When an object does not support attribute references orattribute assignments at all,TypeError is raised.)

exceptionEOFError

Raised when theinput() function hits an end-of-file condition (EOF)without reading any data. (N.B.: theio.IOBase.read() andio.IOBase.readline() methods return an empty string when they hit EOF.)

exceptionFloatingPointError

Not currently used.

exceptionGeneratorExit

Raised when agenerator orcoroutine is closed;seegenerator.close() andcoroutine.close(). Itdirectly inherits fromBaseException instead ofException sinceit is technically not an error.

exceptionImportError

Raised when theimport statement has troubles trying toload a module. Also raised when the “from list” infrom...importhas a name that cannot be found.

Thename andpath attributes can be set using keyword-onlyarguments to the constructor. When set they represent the name of the modulethat was attempted to be imported and the path to any file which triggeredthe exception, respectively.

Changed in version 3.3:Added thename andpath attributes.

exceptionModuleNotFoundError

A subclass ofImportError which is raised byimportwhen a module could not be located. It is also raised whenNoneis found insys.modules.

New in version 3.6.

exceptionIndexError

Raised when a sequence subscript is out of range. (Slice indices aresilently truncated to fall in the allowed range; if an index is not aninteger,TypeError is raised.)

exceptionKeyError

Raised when a mapping (dictionary) key is not found in the set of existing keys.

exceptionKeyboardInterrupt

Raised when the user hits the interrupt key (normallyControl-C orDelete). During execution, a check for interrupts is maderegularly. The exception inherits fromBaseException so as to not beaccidentally caught by code that catchesException and thus preventthe interpreter from exiting.

exceptionMemoryError

Raised when an operation runs out of memory but the situation may still berescued (by deleting some objects). The associated value is a string indicatingwhat kind of (internal) operation ran out of memory. Note that because of theunderlying memory management architecture (C’smalloc() function), theinterpreter may not always be able to completely recover from this situation; itnevertheless raises an exception so that a stack traceback can be printed, incase a run-away program was the cause.

exceptionNameError

Raised when a local or global name is not found. This applies only tounqualified names. The associated value is an error message that includes thename that could not be found.

exceptionNotImplementedError

This exception is derived fromRuntimeError. In user defined baseclasses, abstract methods should raise this exception when they requirederived classes to override the method, or while the class is beingdeveloped to indicate that the real implementation still needs to be added.

Note

It should not be used to indicate that an operator or method is notmeant to be supported at all – in that case either leave the operator /method undefined or, if a subclass, set it toNone.

Note

NotImplementedError andNotImplemented are not interchangeable,even though they have similar names and purposes. SeeNotImplemented for details on when to use it.

exceptionOSError([arg])
exceptionOSError(errno,strerror[,filename[,winerror[,filename2]]])

This exception is raised when a system function returns a system-relatederror, including I/O failures such as “file not found” or “disk full”(not for illegal argument types or other incidental errors).

The second form of the constructor sets the corresponding attributes,described below. The attributes default toNone if notspecified. For backwards compatibility, if three arguments are passed,theargs attribute contains only a 2-tupleof the first two constructor arguments.

The constructor often actually returns a subclass ofOSError, asdescribed inOS exceptions below. The particular subclass depends onthe finalerrno value. This behaviour only occurs whenconstructingOSError directly or via an alias, and is notinherited when subclassing.

errno

A numeric error code from the C variableerrno.

winerror

Under Windows, this gives you the nativeWindows error code. Theerrno attribute is then an approximatetranslation, in POSIX terms, of that native error code.

Under Windows, if thewinerror constructor argument is an integer,theerrno attribute is determined from the Windows error code,and theerrno argument is ignored. On other platforms, thewinerror argument is ignored, and thewinerror attributedoes not exist.

strerror

The corresponding error message, as provided bythe operating system. It is formatted by the Cfunctionsperror() under POSIX, andFormatMessage()under Windows.

filename
filename2

For exceptions that involve a file system path (such asopen() oros.unlink()),filename is the file name passed to the function.For functions that involve two file system paths (such asos.rename()),filename2 corresponds to the secondfile name passed to the function.

Changed in version 3.3:EnvironmentError,IOError,WindowsError,socket.error,select.error andmmap.error have been merged intoOSError, and theconstructor may return a subclass.

Changed in version 3.4:Thefilename attribute is now the original file name passed tothe function, instead of the name encoded to or decoded from thefilesystem encoding. Also, thefilename2 constructor argument andattribute was added.

exceptionOverflowError

Raised when the result of an arithmetic operation is too large to berepresented. This cannot occur for integers (which would rather raiseMemoryError than give up). However, for historical reasons,OverflowError is sometimes raised for integers that are outside a requiredrange. Because of the lack of standardization of floating point exceptionhandling in C, most floating point operations are not checked.

exceptionRecursionError

This exception is derived fromRuntimeError. It is raised when theinterpreter detects that the maximum recursion depth (seesys.getrecursionlimit()) is exceeded.

New in version 3.5:Previously, a plainRuntimeError was raised.

exceptionReferenceError

This exception is raised when a weak reference proxy, created by theweakref.proxy() function, is used to access an attribute of the referentafter it has been garbage collected. For more information on weak references,see theweakref module.

exceptionRuntimeError

Raised when an error is detected that doesn’t fall in any of the othercategories. The associated value is a string indicating what precisely wentwrong.

exceptionStopIteration

Raised by built-in functionnext() and aniterator’s__next__() method to signal that there are no furtheritems produced by the iterator.

The exception object has a single attributevalue, which isgiven as an argument when constructing the exception, and defaultstoNone.

When agenerator orcoroutine functionreturns, a newStopIteration instance israised, and the value returned by the function is used as thevalue parameter to the constructor of the exception.

If a generator code directly or indirectly raisesStopIteration,it is converted into aRuntimeError (retaining theStopIteration as the new exception’s cause).

Changed in version 3.3:Addedvalue attribute and the ability for generator functions touse it to return a value.

Changed in version 3.5:Introduced the RuntimeError transformation viafrom__future__importgenerator_stop, seePEP 479.

Changed in version 3.7:EnablePEP 479 for all code by default: aStopIterationerror raised in a generator is transformed into aRuntimeError.

exceptionStopAsyncIteration

Must be raised by__anext__() method of anasynchronous iterator object to stop the iteration.

New in version 3.5.

exceptionSyntaxError

Raised when the parser encounters a syntax error. This may occur in animport statement, in a call to the built-in functionsexec()oreval(), or when reading the initial script or standard input(also interactively).

Thestr() of the exception instance returns only the error message.

filename

The name of the file the syntax error occurred in.

lineno

Which line number in the file the error occurred in. This is1-indexed: the first line in the file has alineno of 1.

offset

The column in the line where the error occurred. This is1-indexed: the first character in the line has anoffset of 1.

text

The source code text involved in the error.

exceptionIndentationError

Base class for syntax errors related to incorrect indentation. This is asubclass ofSyntaxError.

exceptionTabError

Raised when indentation contains an inconsistent use of tabs and spaces.This is a subclass ofIndentationError.

exceptionSystemError

Raised when the interpreter finds an internal error, but the situation does notlook so serious to cause it to abandon all hope. The associated value is astring indicating what went wrong (in low-level terms).

You should report this to the author or maintainer of your Python interpreter.Be sure to report the version of the Python interpreter (sys.version; it isalso printed at the start of an interactive Python session), the exact errormessage (the exception’s associated value) and if possible the source of theprogram that triggered the error.

exceptionSystemExit

This exception is raised by thesys.exit() function. It inherits fromBaseException instead ofException so that it is not accidentallycaught by code that catchesException. This allows the exception toproperly propagate up and cause the interpreter to exit. When it is nothandled, the Python interpreter exits; no stack traceback is printed. Theconstructor accepts the same optional argument passed tosys.exit().If the value is an integer, it specifies the system exit status (passed toC’sexit() function); if it isNone, the exit status is zero; ifit has another type (such as a string), the object’s value is printed andthe exit status is one.

A call tosys.exit() is translated into an exception so that clean-uphandlers (finally clauses oftry statements) can beexecuted, and so that a debugger can execute a script without running the riskof losing control. Theos._exit() function can be used if it isabsolutely positively necessary to exit immediately (for example, in the childprocess after a call toos.fork()).

code

The exit status or error message that is passed to the constructor.(Defaults toNone.)

exceptionTypeError

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

This exception may be raised by user code to indicate that an attemptedoperation on an object is not supported, and is not meant to be. If an objectis meant to support a given operation but has not yet provided animplementation,NotImplementedError is the proper exception to raise.

Passing arguments of the wrong type (e.g. passing alist when anint is expected) should result in aTypeError, but passingarguments with the wrong value (e.g. a number outside expected boundaries)should result in aValueError.

exceptionUnboundLocalError

Raised when a reference is made to a local variable in a function or method, butno value has been bound to that variable. This is a subclass ofNameError.

exceptionUnicodeError

Raised when a Unicode-related encoding or decoding error occurs. It is asubclass ofValueError.

UnicodeError has attributes that describe the encoding or decodingerror. For example,err.object[err.start:err.end] gives the particularinvalid input that the codec failed on.

encoding

The name of the encoding that raised the error.

reason

A string describing the specific codec error.

object

The object the codec was attempting to encode or decode.

start

The first index of invalid data inobject.

end

The index after the last invalid data inobject.

exceptionUnicodeEncodeError

Raised when a Unicode-related error occurs during encoding. It is a subclass ofUnicodeError.

exceptionUnicodeDecodeError

Raised when a Unicode-related error occurs during decoding. It is a subclass ofUnicodeError.

exceptionUnicodeTranslateError

Raised when a Unicode-related error occurs during translating. It is a subclassofUnicodeError.

exceptionValueError

Raised when an operation or function receives an argument that has theright type but an inappropriate value, and the situation is not described by amore precise exception such asIndexError.

exceptionZeroDivisionError

Raised when the second argument of a division or modulo operation is zero. Theassociated value is a string indicating the type of the operands and theoperation.

The following exceptions are kept for compatibility with previous versions;starting from Python 3.3, they are aliases ofOSError.

exceptionEnvironmentError
exceptionIOError
exceptionWindowsError

Only available on Windows.

OS exceptions

The following exceptions are subclasses ofOSError, they get raiseddepending on the system error code.

exceptionBlockingIOError

Raised when an operation would block on an object (e.g. socket) setfor non-blocking operation.Corresponds toerrnoEAGAIN,EALREADY,EWOULDBLOCK andEINPROGRESS.

In addition to those ofOSError,BlockingIOError can haveone more attribute:

characters_written

An integer containing the number of characters written to the streambefore it blocked. This attribute is available when using thebuffered I/O classes from theio module.

exceptionChildProcessError

Raised when an operation on a child process failed.Corresponds toerrnoECHILD.

exceptionConnectionError

A base class for connection-related issues.

Subclasses areBrokenPipeError,ConnectionAbortedError,ConnectionRefusedError andConnectionResetError.

exceptionBrokenPipeError

A subclass ofConnectionError, raised when trying to write on apipe while the other end has been closed, or trying to write on a socketwhich has been shutdown for writing.Corresponds toerrnoEPIPE andESHUTDOWN.

exceptionConnectionAbortedError

A subclass ofConnectionError, raised when a connection attemptis aborted by the peer.Corresponds toerrnoECONNABORTED.

exceptionConnectionRefusedError

A subclass ofConnectionError, raised when a connection attemptis refused by the peer.Corresponds toerrnoECONNREFUSED.

exceptionConnectionResetError

A subclass ofConnectionError, raised when a connection isreset by the peer.Corresponds toerrnoECONNRESET.

exceptionFileExistsError

Raised when trying to create a file or directory which already exists.Corresponds toerrnoEEXIST.

exceptionFileNotFoundError

Raised when a file or directory is requested but doesn’t exist.Corresponds toerrnoENOENT.

exceptionInterruptedError

Raised when a system call is interrupted by an incoming signal.Corresponds toerrnoEINTR.

Changed in version 3.5:Python now retries system calls when a syscall is interrupted by asignal, except if the signal handler raises an exception (seePEP 475for the rationale), instead of raisingInterruptedError.

exceptionIsADirectoryError

Raised when a file operation (such asos.remove()) is requestedon a directory.Corresponds toerrnoEISDIR.

exceptionNotADirectoryError

Raised when a directory operation (such asos.listdir()) is requestedon something which is not a directory.Corresponds toerrnoENOTDIR.

exceptionPermissionError

Raised when trying to run an operation without the adequate accessrights - for example filesystem permissions.Corresponds toerrnoEACCES andEPERM.

exceptionProcessLookupError

Raised when a given process doesn’t exist.Corresponds toerrnoESRCH.

exceptionTimeoutError

Raised when a system function timed out at the system level.Corresponds toerrnoETIMEDOUT.

New in version 3.3:All the aboveOSError subclasses were added.

See also

PEP 3151 - Reworking the OS and IO exception hierarchy

Warnings

The following exceptions are used as warning categories; see theWarning Categories documentation for more details.

exceptionWarning

Base class for warning categories.

exceptionUserWarning

Base class for warnings generated by user code.

exceptionDeprecationWarning

Base class for warnings about deprecated features when those warnings areintended for other Python developers.

exceptionPendingDeprecationWarning

Base class for warnings about features which are obsolete andexpected to be deprecated in the future, but are not deprecatedat the moment.

This class is rarely used as emitting a warning about a possibleupcoming deprecation is unusual, andDeprecationWarningis preferred for already active deprecations.

exceptionSyntaxWarning

Base class for warnings about dubious syntax.

exceptionRuntimeWarning

Base class for warnings about dubious runtime behavior.

exceptionFutureWarning

Base class for warnings about deprecated features when those warnings areintended for end users of applications that are written in Python.

exceptionImportWarning

Base class for warnings about probable mistakes in module imports.

exceptionUnicodeWarning

Base class for warnings related to Unicode.

exceptionBytesWarning

Base class for warnings related tobytes andbytearray.

exceptionResourceWarning

Base class for warnings related to resource usage. Ignored by the defaultwarning filters.

New in version 3.2.

Exception hierarchy

The class hierarchy for built-in exceptions is:

BaseException+--SystemExit+--KeyboardInterrupt+--GeneratorExit+--Exception+--StopIteration+--StopAsyncIteration+--ArithmeticError|+--FloatingPointError|+--OverflowError|+--ZeroDivisionError+--AssertionError+--AttributeError+--BufferError+--EOFError+--ImportError|+--ModuleNotFoundError+--LookupError|+--IndexError|+--KeyError+--MemoryError+--NameError|+--UnboundLocalError+--OSError|+--BlockingIOError|+--ChildProcessError|+--ConnectionError||+--BrokenPipeError||+--ConnectionAbortedError||+--ConnectionRefusedError||+--ConnectionResetError|+--FileExistsError|+--FileNotFoundError|+--InterruptedError|+--IsADirectoryError|+--NotADirectoryError|+--PermissionError|+--ProcessLookupError|+--TimeoutError+--ReferenceError+--RuntimeError|+--NotImplementedError|+--RecursionError+--SyntaxError|+--IndentationError|+--TabError+--SystemError+--TypeError+--ValueError|+--UnicodeError|+--UnicodeDecodeError|+--UnicodeEncodeError|+--UnicodeTranslateError+--Warning+--DeprecationWarning+--PendingDeprecationWarning+--RuntimeWarning+--SyntaxWarning+--UserWarning+--FutureWarning+--ImportWarning+--UnicodeWarning+--BytesWarning+--ResourceWarning