Remove outdated include; this include was breaking OS X builds using
[python.git] / Doc / library / exceptions.rst
blob2f07d291840e391b26aa133a5f38fc4ffdd3f4d8
1 .. _bltin-exceptions:
3 Built-in Exceptions
4 ===================
6 .. module:: exceptions
7    :synopsis: Standard exception classes.
10 Exceptions should be class objects.   The exceptions are defined in the module
11 :mod:`exceptions`.  This module never needs to be imported explicitly: the
12 exceptions are provided in the built-in namespace as well as the
13 :mod:`exceptions` module.
15 .. index::
16    statement: try
17    statement: except
19 For class exceptions, in a :keyword:`try` statement with an :keyword:`except`
20 clause that mentions a particular class, that clause also handles any exception
21 classes derived from that class (but not exception classes from which *it* is
22 derived).  Two exception classes that are not related via subclassing are never
23 equivalent, even if they have the same name.
25 .. index:: statement: raise
27 The built-in exceptions listed below can be generated by the interpreter or
28 built-in functions.  Except where mentioned, they have an "associated value"
29 indicating the detailed cause of the error. This may be a string or a tuple
30 containing several items of information (e.g., an error code and a string
31 explaining the code). The associated value is the second argument to the
32 :keyword:`raise` statement.  If the exception class is derived from the standard
33 root class :exc:`BaseException`, the associated value is present as the
34 exception instance's :attr:`args` attribute.
36 User code can raise built-in exceptions.  This can be used to test an exception
37 handler or to report an error condition "just like" the situation in which the
38 interpreter raises the same exception; but beware that there is nothing to
39 prevent user code from raising an inappropriate error.
41 The built-in exception classes can be sub-classed to define new exceptions;
42 programmers are encouraged to at least derive new exceptions from the
43 :exc:`Exception` class and not :exc:`BaseException`.  More information on
44 defining exceptions is available in the Python Tutorial under
45 :ref:`tut-userexceptions`.
47 The following exceptions are only used as base classes for other exceptions.
50 .. exception:: BaseException
52    The base class for all built-in exceptions.  It is not meant to be directly
53    inherited by user-defined classes (for that use :exc:`Exception`).  If
54    :func:`str` or :func:`unicode` is called on an instance of this class, the
55    representation of the argument(s) to the instance are returned or the empty
56    string when there were no arguments.  All arguments are  stored in :attr:`args`
57    as a tuple.
59    .. versionadded:: 2.5
62 .. exception:: Exception
64    All built-in, non-system-exiting exceptions are derived from this class.  All
65    user-defined exceptions should also be derived from this class.
67    .. versionchanged:: 2.5
68       Changed to inherit from :exc:`BaseException`.
71 .. exception:: StandardError
73    The base class for all built-in exceptions except :exc:`StopIteration`,
74    :exc:`GeneratorExit`, :exc:`KeyboardInterrupt` and :exc:`SystemExit`.
75    :exc:`StandardError` itself is derived from :exc:`Exception`.
78 .. exception:: ArithmeticError
80    The base class for those built-in exceptions that are raised for various
81    arithmetic errors: :exc:`OverflowError`, :exc:`ZeroDivisionError`,
82    :exc:`FloatingPointError`.
85 .. exception:: LookupError
87    The base class for the exceptions that are raised when a key or index used on
88    a mapping or sequence is invalid: :exc:`IndexError`, :exc:`KeyError`.  This
89    can be raised directly by :func:`codecs.lookup`.
92 .. exception:: EnvironmentError
94    The base class for exceptions that can occur outside the Python system:
95    :exc:`IOError`, :exc:`OSError`.  When exceptions of this type are created with a
96    2-tuple, the first item is available on the instance's :attr:`errno` attribute
97    (it is assumed to be an error number), and the second item is available on the
98    :attr:`strerror` attribute (it is usually the associated error message).  The
99    tuple itself is also available on the :attr:`args` attribute.
101    .. versionadded:: 1.5.2
103    When an :exc:`EnvironmentError` exception is instantiated with a 3-tuple, the
104    first two items are available as above, while the third item is available on the
105    :attr:`filename` attribute.  However, for backwards compatibility, the
106    :attr:`args` attribute contains only a 2-tuple of the first two constructor
107    arguments.
109    The :attr:`filename` attribute is ``None`` when this exception is created with
110    other than 3 arguments.  The :attr:`errno` and :attr:`strerror` attributes are
111    also ``None`` when the instance was created with other than 2 or 3 arguments.
112    In this last case, :attr:`args` contains the verbatim constructor arguments as a
113    tuple.
115 The following exceptions are the exceptions that are actually raised.
118 .. exception:: AssertionError
120    .. index:: statement: assert
122    Raised when an :keyword:`assert` statement fails.
125 .. exception:: AttributeError
127    Raised when an attribute reference (see :ref:`attribute-references`) or
128    assignment fails.  (When an object does not support attribute references or
129    attribute assignments at all, :exc:`TypeError` is raised.)
132 .. exception:: EOFError
134    Raised when one of the built-in functions (:func:`input` or :func:`raw_input`)
135    hits an end-of-file condition (EOF) without reading any data. (N.B.: the
136    :meth:`file.read` and :meth:`file.readline` methods return an empty string
137    when they hit EOF.)
140 .. exception:: FloatingPointError
142    Raised when a floating point operation fails.  This exception is always defined,
143    but can only be raised when Python is configured with the
144    :option:`--with-fpectl` option, or the :const:`WANT_SIGFPE_HANDLER` symbol is
145    defined in the :file:`pyconfig.h` file.
148 .. exception:: GeneratorExit
150    Raise when a :term:`generator`\'s :meth:`close` method is called.  It
151    directly inherits from :exc:`BaseException` instead of :exc:`StandardError` since
152    it is technically not an error.
154    .. versionadded:: 2.5
156    .. versionchanged:: 2.6
157       Changed to inherit from :exc:`BaseException`.
159 .. exception:: IOError
161    Raised when an I/O operation (such as a :keyword:`print` statement, the built-in
162    :func:`open` function or a method of a file object) fails for an I/O-related
163    reason, e.g., "file not found" or "disk full".
165    This class is derived from :exc:`EnvironmentError`.  See the discussion above
166    for more information on exception instance attributes.
168    .. versionchanged:: 2.6
169       Changed :exc:`socket.error` to use this as a base class.
172 .. exception:: ImportError
174    Raised when an :keyword:`import` statement fails to find the module definition
175    or when a ``from ... import`` fails to find a name that is to be imported.
178 .. exception:: IndexError
180    Raised when a sequence subscript is out of range.  (Slice indices are silently
181    truncated to fall in the allowed range; if an index is not a plain integer,
182    :exc:`TypeError` is raised.)
184    .. XXX xref to sequences
187 .. exception:: KeyError
189    Raised when a mapping (dictionary) key is not found in the set of existing keys.
191    .. XXX xref to mapping objects?
194 .. exception:: KeyboardInterrupt
196    Raised when the user hits the interrupt key (normally :kbd:`Control-C` or
197    :kbd:`Delete`).  During execution, a check for interrupts is made regularly.
198    Interrupts typed when a built-in function :func:`input` or :func:`raw_input` is
199    waiting for input also raise this exception. The exception inherits from
200    :exc:`BaseException` so as to not be accidentally caught by code that catches
201    :exc:`Exception` and thus prevent the interpreter from exiting.
203    .. versionchanged:: 2.5
204       Changed to inherit from :exc:`BaseException`.
207 .. exception:: MemoryError
209    Raised when an operation runs out of memory but the situation may still be
210    rescued (by deleting some objects).  The associated value is a string indicating
211    what kind of (internal) operation ran out of memory. Note that because of the
212    underlying memory management architecture (C's :cfunc:`malloc` function), the
213    interpreter may not always be able to completely recover from this situation; it
214    nevertheless raises an exception so that a stack traceback can be printed, in
215    case a run-away program was the cause.
218 .. exception:: NameError
220    Raised when a local or global name is not found.  This applies only to
221    unqualified names.  The associated value is an error message that includes the
222    name that could not be found.
225 .. exception:: NotImplementedError
227    This exception is derived from :exc:`RuntimeError`.  In user defined base
228    classes, abstract methods should raise this exception when they require derived
229    classes to override the method.
231    .. versionadded:: 1.5.2
234 .. exception:: OSError
236    .. index:: module: errno
238    This exception is derived from :exc:`EnvironmentError`.  It is raised when a
239    function returns a system-related error (not for illegal argument types or
240    other incidental errors).  The :attr:`errno` attribute is a numeric error
241    code from :cdata:`errno`, and the :attr:`strerror` attribute is the
242    corresponding string, as would be printed by the C function :cfunc:`perror`.
243    See the module :mod:`errno`, which contains names for the error codes defined
244    by the underlying operating system.
246    For exceptions that involve a file system path (such as :func:`chdir` or
247    :func:`unlink`), the exception instance will contain a third attribute,
248    :attr:`filename`, which is the file name passed to the function.
250    .. versionadded:: 1.5.2
253 .. exception:: OverflowError
255    Raised when the result of an arithmetic operation is too large to be
256    represented.  This cannot occur for long integers (which would rather raise
257    :exc:`MemoryError` than give up) and for most operations with plain integers,
258    which return a long integer instead.  Because of the lack of standardization
259    of floating point exception handling in C, most floating point operations
260    also aren't checked.
263 .. exception:: ReferenceError
265    This exception is raised when a weak reference proxy, created by the
266    :func:`weakref.proxy` function, is used to access an attribute of the referent
267    after it has been garbage collected. For more information on weak references,
268    see the :mod:`weakref` module.
270    .. versionadded:: 2.2
271       Previously known as the :exc:`weakref.ReferenceError` exception.
274 .. exception:: RuntimeError
276    Raised when an error is detected that doesn't fall in any of the other
277    categories.  The associated value is a string indicating what precisely went
278    wrong.  (This exception is mostly a relic from a previous version of the
279    interpreter; it is not used very much any more.)
282 .. exception:: StopIteration
284    Raised by an :term:`iterator`\'s :meth:`~iterator.next` method to signal that
285    there are no further values.  This is derived from :exc:`Exception` rather
286    than :exc:`StandardError`, since this is not considered an error in its
287    normal application.
289    .. versionadded:: 2.2
292 .. exception:: SyntaxError
294    Raised when the parser encounters a syntax error.  This may occur in an
295    :keyword:`import` statement, in an :keyword:`exec` statement, in a call to the
296    built-in function :func:`eval` or :func:`input`, or when reading the initial
297    script or standard input (also interactively).
299    Instances of this class have attributes :attr:`filename`, :attr:`lineno`,
300    :attr:`offset` and :attr:`text` for easier access to the details.  :func:`str`
301    of the exception instance returns only the message.
304 .. exception:: SystemError
306    Raised when the interpreter finds an internal error, but the situation does not
307    look so serious to cause it to abandon all hope. The associated value is a
308    string indicating what went wrong (in low-level terms).
310    You should report this to the author or maintainer of your Python interpreter.
311    Be sure to report the version of the Python interpreter (``sys.version``; it is
312    also printed at the start of an interactive Python session), the exact error
313    message (the exception's associated value) and if possible the source of the
314    program that triggered the error.
317 .. exception:: SystemExit
319    This exception is raised by the :func:`sys.exit` function.  When it is not
320    handled, the Python interpreter exits; no stack traceback is printed.  If the
321    associated value is a plain integer, it specifies the system exit status (passed
322    to C's :cfunc:`exit` function); if it is ``None``, the exit status is zero; if
323    it has another type (such as a string), the object's value is printed and the
324    exit status is one.
326    Instances have an attribute :attr:`code` which is set to the proposed exit
327    status or error message (defaulting to ``None``). Also, this exception derives
328    directly from :exc:`BaseException` and not :exc:`StandardError`, since it is not
329    technically an error.
331    A call to :func:`sys.exit` is translated into an exception so that clean-up
332    handlers (:keyword:`finally` clauses of :keyword:`try` statements) can be
333    executed, and so that a debugger can execute a script without running the risk
334    of losing control.  The :func:`os._exit` function can be used if it is
335    absolutely positively necessary to exit immediately (for example, in the child
336    process after a call to :func:`fork`).
338    The exception inherits from :exc:`BaseException` instead of :exc:`StandardError`
339    or :exc:`Exception` so that it is not accidentally caught by code that catches
340    :exc:`Exception`.  This allows the exception to properly propagate up and cause
341    the interpreter to exit.
343    .. versionchanged:: 2.5
344       Changed to inherit from :exc:`BaseException`.
347 .. exception:: TypeError
349    Raised when an operation or function is applied to an object of inappropriate
350    type.  The associated value is a string giving details about the type mismatch.
353 .. exception:: UnboundLocalError
355    Raised when a reference is made to a local variable in a function or method, but
356    no value has been bound to that variable.  This is a subclass of
357    :exc:`NameError`.
359    .. versionadded:: 2.0
362 .. exception:: UnicodeError
364    Raised when a Unicode-related encoding or decoding error occurs.  It is a
365    subclass of :exc:`ValueError`.
367    .. versionadded:: 2.0
370 .. exception:: UnicodeEncodeError
372    Raised when a Unicode-related error occurs during encoding.  It is a subclass of
373    :exc:`UnicodeError`.
375    .. versionadded:: 2.3
378 .. exception:: UnicodeDecodeError
380    Raised when a Unicode-related error occurs during decoding.  It is a subclass of
381    :exc:`UnicodeError`.
383    .. versionadded:: 2.3
386 .. exception:: UnicodeTranslateError
388    Raised when a Unicode-related error occurs during translating.  It is a subclass
389    of :exc:`UnicodeError`.
391    .. versionadded:: 2.3
394 .. exception:: ValueError
396    Raised when a built-in operation or function receives an argument that has the
397    right type but an inappropriate value, and the situation is not described by a
398    more precise exception such as :exc:`IndexError`.
401 .. exception:: VMSError
403    Only available on VMS.  Raised when a VMS-specific error occurs.
406 .. exception:: WindowsError
408    Raised when a Windows-specific error occurs or when the error number does not
409    correspond to an :cdata:`errno` value.  The :attr:`winerror` and
410    :attr:`strerror` values are created from the return values of the
411    :cfunc:`GetLastError` and :cfunc:`FormatMessage` functions from the Windows
412    Platform API. The :attr:`errno` value maps the :attr:`winerror` value to
413    corresponding ``errno.h`` values. This is a subclass of :exc:`OSError`.
415    .. versionadded:: 2.0
417    .. versionchanged:: 2.5
418       Previous versions put the :cfunc:`GetLastError` codes into :attr:`errno`.
421 .. exception:: ZeroDivisionError
423    Raised when the second argument of a division or modulo operation is zero.  The
424    associated value is a string indicating the type of the operands and the
425    operation.
427 The following exceptions are used as warning categories; see the :mod:`warnings`
428 module for more information.
431 .. exception:: Warning
433    Base class for warning categories.
436 .. exception:: UserWarning
438    Base class for warnings generated by user code.
441 .. exception:: DeprecationWarning
443    Base class for warnings about deprecated features.
446 .. exception:: PendingDeprecationWarning
448    Base class for warnings about features which will be deprecated in the future.
451 .. exception:: SyntaxWarning
453    Base class for warnings about dubious syntax
456 .. exception:: RuntimeWarning
458    Base class for warnings about dubious runtime behavior.
461 .. exception:: FutureWarning
463    Base class for warnings about constructs that will change semantically in the
464    future.
467 .. exception:: ImportWarning
469    Base class for warnings about probable mistakes in module imports.
471    .. versionadded:: 2.5
474 .. exception:: UnicodeWarning
476    Base class for warnings related to Unicode.
478    .. versionadded:: 2.5
481 Exception hierarchy
482 -------------------
484 The class hierarchy for built-in exceptions is:
486 .. literalinclude:: ../../Lib/test/exception_hierarchy.txt