5. 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.
5.1. Base classes¶
The following exceptions are used mostly as base classes for other exceptions.
- exception
BaseException¶ The base class for all built-in exceptions. It is not meant to be directlyinherited by user-defined classes (for that, use
Exception). 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 (like
OSError) 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)
- exception
Exception¶ All built-in, non-system-exiting exceptions are derived from this class. Alluser-defined exceptions should also be derived from this class.
- exception
ArithmeticError¶ The base class for those built-in exceptions that are raised for variousarithmetic errors:
OverflowError,ZeroDivisionError,FloatingPointError.
- exception
LookupError¶ 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().
5.2. Concrete exceptions¶
The following exceptions are the exceptions that are usually raised.
- exception
AttributeError¶ Raised when an attribute reference (seeAttribute references) orassignment fails. (When an object does not support attribute references orattribute assignments at all,
TypeErroris raised.)
- exception
EOFError¶ Raised when the
input()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.)
- exception
FloatingPointError¶ Raised when a floating point operation fails. This exception is always defined,but can only be raised when Python is configured with the
--with-fpectloption, or theWANT_SIGFPE_HANDLERsymbol isdefined in thepyconfig.hfile.
- exception
GeneratorExit¶ Raised when agenerator orcoroutine is closed;see
generator.close()andcoroutine.close(). Itdirectly inherits fromBaseExceptioninstead ofExceptionsinceit is technically not an error.
- exception
ImportError¶ Raised when an
importstatement fails to find the module definitionor when afrom...importfails to find a name that is to be imported.The
nameandpathattributes 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 the
nameandpathattributes.
- exception
IndexError¶ 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,
TypeErroris raised.)
- exception
KeyError¶ Raised when a mapping (dictionary) key is not found in the set of existing keys.
- exception
KeyboardInterrupt¶ Raised when the user hits the interrupt key (normallyControl-C orDelete). During execution, a check for interrupts is maderegularly. The exception inherits from
BaseExceptionso as to not beaccidentally caught by code that catchesExceptionand thus preventthe interpreter from exiting.
- exception
MemoryError¶ 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’s
malloc()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.
- exception
NameError¶ 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.
- exception
NotImplementedError¶ This exception is derived from
RuntimeError. In user defined baseclasses, abstract methods should raise this exception when they require derivedclasses to override the method.
- exception
OSError([arg])¶ - exception
OSError(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 to
Noneif notspecified. For backwards compatibility, if three arguments are passed,theargsattribute contains only a 2-tupleof the first two constructor arguments.The constructor often actually returns a subclass of
OSError, asdescribed inOS exceptions below. The particular subclass depends onthe finalerrnovalue. This behaviour only occurs whenconstructingOSErrordirectly or via an alias, and is notinherited when subclassing.errno¶A numeric error code from the C variable
errno.
winerror¶Under Windows, this gives you the nativeWindows error code. The
errnoattribute is then an approximatetranslation, in POSIX terms, of that native error code.Under Windows, if thewinerror constructor argument is an integer,the
errnoattribute is determined from the Windows error code,and theerrno argument is ignored. On other platforms, thewinerror argument is ignored, and thewinerrorattributedoes not exist.
strerror¶The corresponding error message, as provided bythe operating system. It is formatted by the Cfunctions
perror()under POSIX, andFormatMessage()under Windows.
filename¶filename2¶For exceptions that involve a file system path (such as
open()oros.unlink()),filenameis the file name passed to the function.For functions that involve two file system paths (such asos.rename()),filename2corresponds to the secondfile name passed to the function.
Changed in version 3.3:
EnvironmentError,IOError,WindowsError,socket.error,select.errorandmmap.errorhave been merged intoOSError, and theconstructor may return a subclass.Changed in version 3.4:The
filenameattribute 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.
- exception
OverflowError¶ Raised when the result of an arithmetic operation is too large to berepresented. This cannot occur for integers (which would rather raise
MemoryErrorthan 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.
- exception
RecursionError¶ This exception is derived from
RuntimeError. It is raised when theinterpreter detects that the maximum recursion depth (seesys.getrecursionlimit()) is exceeded.New in version 3.5:Previously, a plain
RuntimeErrorwas raised.
- exception
ReferenceError¶ This exception is raised when a weak reference proxy, created by the
weakref.proxy()function, is used to access an attribute of the referentafter it has been garbage collected. For more information on weak references,see theweakrefmodule.
- exception
RuntimeError¶ 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.
- exception
StopIteration¶ Raised by built-in function
next()and aniterator’s__next__()method to signal that there are no furtheritems produced by the iterator.The exception object has a single attribute
value, which isgiven as an argument when constructing the exception, and defaultstoNone.When agenerator orcoroutine functionreturns, a new
StopIterationinstance israised, and the value returned by the function is used as thevalueparameter to the constructor of the exception.If a generator function defined in the presence of a
from__future__importgenerator_stopdirective raisesStopIteration, it will beconverted into aRuntimeError(retaining theStopIterationas the new exception’s cause).Changed in version 3.3:Added
valueattribute and the ability for generator functions touse it to return a value.Changed in version 3.5:Introduced the RuntimeError transformation.
- exception
StopAsyncIteration¶ Must be raised by
__anext__()method of anasynchronous iterator object to stop the iteration.New in version 3.5.
- exception
SyntaxError¶ Raised when the parser encounters a syntax error. This may occur in an
importstatement, in a call to the built-in functionsexec()oreval(), or when reading the initial script or standard input(also interactively).Instances of this class have attributes
filename,lineno,offsetandtextfor easier access to the details.str()of the exception instance returns only the message.
- exception
IndentationError¶ Base class for syntax errors related to incorrect indentation. This is asubclass of
SyntaxError.
- exception
TabError¶ Raised when indentation contains an inconsistent use of tabs and spaces.This is a subclass of
IndentationError.
- exception
SystemError¶ 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.
- exception
SystemExit¶ This exception is raised by the
sys.exit()function. It inherits fromBaseExceptioninstead ofExceptionso 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 to
sys.exit()is translated into an exception so that clean-uphandlers (finallyclauses oftrystatements) 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 to
None.)
- exception
TypeError¶ 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.
- exception
UnboundLocalError¶ 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 of
NameError.
- exception
UnicodeError¶ Raised when a Unicode-related encoding or decoding error occurs. It is asubclass of
ValueError.UnicodeErrorhas 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.
- exception
UnicodeEncodeError¶ Raised when a Unicode-related error occurs during encoding. It is a subclass of
UnicodeError.
- exception
UnicodeDecodeError¶ Raised when a Unicode-related error occurs during decoding. It is a subclass of
UnicodeError.
- exception
UnicodeTranslateError¶ Raised when a Unicode-related error occurs during translating. It is a subclassof
UnicodeError.
- exception
ValueError¶ Raised when a built-in 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 as
IndexError.
- exception
ZeroDivisionError¶ 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.
- exception
EnvironmentError¶
- exception
IOError¶
- exception
WindowsError¶ Only available on Windows.
5.2.1. OS exceptions¶
The following exceptions are subclasses ofOSError, they get raiseddepending on the system error code.
- exception
BlockingIOError¶ Raised when an operation would block on an object (e.g. socket) setfor non-blocking operation.Corresponds to
errnoEAGAIN,EALREADY,EWOULDBLOCKandEINPROGRESS.In addition to those of
OSError,BlockingIOErrorcan haveone more attribute:
- exception
ChildProcessError¶ Raised when an operation on a child process failed.Corresponds to
errnoECHILD.
- exception
ConnectionError¶ A base class for connection-related issues.
Subclasses are
BrokenPipeError,ConnectionAbortedError,ConnectionRefusedErrorandConnectionResetError.
- exception
BrokenPipeError¶ A subclass of
ConnectionError, 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 toerrnoEPIPEandESHUTDOWN.
- exception
ConnectionAbortedError¶ A subclass of
ConnectionError, raised when a connection attemptis aborted by the peer.Corresponds toerrnoECONNABORTED.
- exception
ConnectionRefusedError¶ A subclass of
ConnectionError, raised when a connection attemptis refused by the peer.Corresponds toerrnoECONNREFUSED.
- exception
ConnectionResetError¶ A subclass of
ConnectionError, raised when a connection isreset by the peer.Corresponds toerrnoECONNRESET.
- exception
FileExistsError¶ Raised when trying to create a file or directory which already exists.Corresponds to
errnoEEXIST.
- exception
FileNotFoundError¶ Raised when a file or directory is requested but doesn’t exist.Corresponds to
errnoENOENT.
- exception
InterruptedError¶ Raised when a system call is interrupted by an incoming signal.Corresponds to
errnoEINTR.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 raising
InterruptedError.
- exception
IsADirectoryError¶ Raised when a file operation (such as
os.remove()) is requestedon a directory.Corresponds toerrnoEISDIR.
- exception
NotADirectoryError¶ Raised when a directory operation (such as
os.listdir()) is requestedon something which is not a directory.Corresponds toerrnoENOTDIR.
- exception
PermissionError¶ Raised when trying to run an operation without the adequate accessrights - for example filesystem permissions.Corresponds to
errnoEACCESandEPERM.
- exception
ProcessLookupError¶ Raised when a given process doesn’t exist.Corresponds to
errnoESRCH.
- exception
TimeoutError¶ Raised when a system function timed out at the system level.Corresponds to
errnoETIMEDOUT.
New in version 3.3:All the aboveOSError subclasses were added.
See also
PEP 3151 - Reworking the OS and IO exception hierarchy
5.3. Warnings¶
The following exceptions are used as warning categories; see thewarningsmodule for more information.
- exception
Warning¶ Base class for warning categories.
- exception
UserWarning¶ Base class for warnings generated by user code.
- exception
DeprecationWarning¶ Base class for warnings about deprecated features.
- exception
PendingDeprecationWarning¶ Base class for warnings about features which will be deprecated in the future.
- exception
SyntaxWarning¶ Base class for warnings about dubious syntax.
- exception
RuntimeWarning¶ Base class for warnings about dubious runtime behavior.
- exception
FutureWarning¶ Base class for warnings about constructs that will change semantically in thefuture.
- exception
ImportWarning¶ Base class for warnings about probable mistakes in module imports.
- exception
UnicodeWarning¶ Base class for warnings related to Unicode.
- exception
ResourceWarning¶ Base class for warnings related to resource usage.
New in version 3.2.
5.4. Exception hierarchy¶
The class hierarchy for built-in exceptions is:
BaseException+--SystemExit|+--TaskletExit+--KeyboardInterrupt+--GeneratorExit+--Exception+--StopIteration+--StopAsyncIteration+--ArithmeticError|+--FloatingPointError|+--OverflowError|+--ZeroDivisionError+--AssertionError+--AttributeError+--BufferError+--EOFError+--ImportError+--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
