Movatterモバイル変換


[0]ホーム

URL:


Navigation

Built-in Exceptions

Exceptions should be class objects. The exceptions are defined in the moduleexceptions. This module never needs to be imported explicitly: theexceptions are provided in the built-in namespace as well as theexceptions module.

For class exceptions, 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 tuplecontaining several items of information (e.g., an error code and a stringexplaining the code). The associated value is the second argument to theraise statement. If the exception class is derived from the standardroot classBaseException, the associated value is present as theexception instance’sargs attribute.

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 sub-classed to define new exceptions;programmers are encouraged to at least derive new exceptions from theException class and notBaseException. More information ondefining exceptions is available in the Python Tutorial underUser-defined Exceptions.

The following exceptions are only used 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() orunicode() is called on an instance of this class, therepresentation of the argument(s) to the instance are returned or the emptrystring when there were no arguments. All arguments are stored inargsas a tuple.
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.
exceptionLookupError
The base class for the exceptions that are raised when a key or index used on amapping or sequence is invalid:IndexError,KeyError. This can beraised directly bysys.setdefaultencoding().
exceptionEnvironmentError

The base class for exceptions that can occur outside the Python system:IOError,OSError. When exceptions of this type are created with a2-tuple, the first item is available on the instance’serrno attribute(it is assumed to be an error number), and the second item is available on thestrerror attribute (it is usually the associated error message). Thetuple itself is also available on theargs attribute.

When anEnvironmentError exception is instantiated with a 3-tuple, thefirst two items are available as above, while the third item is available on thefilename attribute. However, for backwards compatibility, theargs attribute contains only a 2-tuple of the first two constructorarguments.

Thefilename attribute isNone when this exception is created withother than 3 arguments. Theerrno andstrerror attributes arealsoNone when the instance was created with other than 2 or 3 arguments.In this last case,args contains the verbatim constructor arguments as atuple.

The following exceptions are the exceptions that are actually 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 one of the built-in functions (input() orraw_input())hits an end-of-file condition (EOF) without reading any data. (N.B.: thefile.read() andfile.readline() methods return an empty stringwhen they hit EOF.)
exceptionFloatingPointError
Raised when a floating point operation fails. This exception is always defined,but can only be raised when Python is configured with the--with-fpectl option, or theWANT_SIGFPE_HANDLER symbol isdefined in thepyconfig.h file.
exceptionGeneratorExit
Raise when agenerator‘sclose() method is called. Itdirectly inherits fromBaseException instead ofException sinceit is technically not an error.
exceptionIOError

Raised when an I/O operation (such as the built-inprint() oropen() functions or a method of a file object) fails for an I/O-relatedreason, e.g., “file not found” or “disk full”.

This class is derived fromEnvironmentError. See the discussion abovefor more information on exception instance attributes.

exceptionImportError
Raised when animport statement fails to find the module definitionor when afrom...import fails to find a name that is to be imported.
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 require derivedclasses to override the method.
exceptionOSError

This exception is derived fromEnvironmentError. It is raised when afunction returns a system-related error (not for illegal argument types orother incidental errors). Theerrno attribute is a numeric errorcode fromerrno, and thestrerror attribute is thecorresponding string, as would be printed by the C functionperror.See the moduleerrno, which contains names for the error codes definedby the underlying operating system.

For exceptions that involve a file system path (such aschdir() orunlink()), the exception instance will contain a third attribute,filename, which is the file name passed to the function.

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). Because of the lack of standardization offloating point exception handling in C, most floating point operations alsoaren’t checked.
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. (This exception is mostly a relic from a previous version of theinterpreter; it is not used very much any more.)
exceptionStopIteration
Raised by builtinnext() and aniterator‘s__next__()method to signal that there are no further values.
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).

Instances of this class have attributesfilename,lineno,offset andtext for easier access to the details.str()of the exception instance returns only the message.

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. When it is nothandled, the Python interpreter exits; no stack traceback is printed. If theassociated value is an integer, it specifies the system exit status (passedto C’sexit function); if it isNone, the exit status is zero;if it has another type (such as a string), the object’s value is printed andthe exit status is one.

Instances have an attributecode which is set to the proposed exitstatus or error message (defaulting toNone). Also, this exception derivesdirectly fromBaseException and notException, since it is nottechnically an error.

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 tofork()).

The exception inherits fromBaseException instead ofException sothat it is not accidentally caught by code that catchesException. Thisallows the exception to properly propagate up and cause the interpreter to exit.

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.
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.
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 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 asIndexError.
exceptionWindowsError
Raised when a Windows-specific error occurs or when the error number does notcorrespond to anerrno value. Thewinerror andstrerror values are created from the return values of theGetLastError andFormatMessage functions from the WindowsPlatform API. Theerrno value maps thewinerror value tocorrespondingerrno.h values. This is a subclass ofOSError.
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 used as warning categories; see thewarningsmodule for more information.

exceptionWarning
Base class for warning categories.
exceptionUserWarning
Base class for warnings generated by user code.
exceptionDeprecationWarning
Base class for warnings about deprecated features.
exceptionPendingDeprecationWarning
Base class for warnings about features which will be deprecated in the future.
exceptionSyntaxWarning
Base class for warnings about dubious syntax
exceptionRuntimeWarning
Base class for warnings about dubious runtime behavior.
exceptionFutureWarning
Base class for warnings about constructs that will change semantically in thefuture.
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 andbuffer.

The class hierarchy for built-in exceptions is:

BaseException+--SystemExit+--KeyboardInterrupt+--GeneratorExit+--Exception+--StopIteration+--ArithmeticError|+--FloatingPointError|+--OverflowError|+--ZeroDivisionError+--AssertionError+--AttributeError+--BufferError+--EnvironmentError|+--IOError|+--OSError|+--WindowsError(Windows)|+--VMSError(VMS)+--EOFError+--ImportError+--LookupError|+--IndexError|+--KeyError+--MemoryError+--NameError|+--UnboundLocalError+--ReferenceError+--RuntimeError|+--NotImplementedError+--SyntaxError|+--IndentationError|+--TabError+--SystemError+--TypeError+--ValueError|+--UnicodeError|+--UnicodeDecodeError|+--UnicodeEncodeError|+--UnicodeTranslateError+--Warning+--DeprecationWarning+--PendingDeprecationWarning+--RuntimeWarning+--SyntaxWarning+--UserWarning+--FutureWarning+--ImportWarning+--UnicodeWarning+--BytesWarning

Previous topic

Built-in Types

Next topic

String Services

This Page

Quick search

Enter search terms or a module, class or function name.

Navigation

©Copyright 1990-2009, Python Software Foundation. Last updated on Feb 14, 2009. Created usingSphinx 0.6.

[8]ページ先頭

©2009-2025 Movatter.jp