rest25/library/exceptions.rst => rest262/library/exceptions.rst
n1+.. _bltin-exceptions:
1
2Built-in Exceptions
3===================
4
5.. module:: exceptions
6   :synopsis: Standard exception classes.
7
8
9Exceptions should be class objects.   The exceptions are defined in the module
10:mod:`exceptions`.  This module never needs to be imported explicitly: the
11exceptions are provided in the built-in namespace as well as the
12:mod:`exceptions` module.
n13- 
14-.. note::
15- 
16-   In past versions of Python string exceptions were supported.  In Python 1.5 and
17-   newer versions, all standard exceptions have been converted to class objects and
18-   users are encouraged to do the same. String exceptions will raise a
19-   ``DeprecationWarning`` in Python 2.5 and newer. In future versions, support for
20-   string exceptions will be removed.
21- 
22-   Two distinct string objects with the same value are considered different
23-   exceptions.  This is done to force programmers to use exception names rather
24-   than their string value when specifying exception handlers. The string value of
25-   all built-in exceptions is their name, but this is not a requirement for user-
26-   defined exceptions or exceptions defined by library modules.
27
28.. index::
29   statement: try
30   statement: except
31
32For class exceptions, in a :keyword:`try` statement with an :keyword:`except`
33clause that mentions a particular class, that clause also handles any exception
34classes derived from that class (but not exception classes from which *it* is
37
38.. index:: statement: raise
39
40The built-in exceptions listed below can be generated by the interpreter or
41built-in functions.  Except where mentioned, they have an "associated value"
42indicating the detailed cause of the error. This may be a string or a tuple
43containing several items of information (e.g., an error code and a string
44explaining the code). The associated value is the second argument to the
n45-:keyword:`raise` statement.  For string exceptions, the associated value itself
n32+:keyword:`raise` statement.  If the exception class is derived from the standard
46-will be stored in the variable named as the second argument of the
47-:keyword:`except` clause (if any).  For class exceptions, that variable receives
48-the exception instance.  If the exception class is derived from the standard
49root class :exc:`BaseException`, the associated value is present as the
n50-exception instance's :attr:`args` attribute.  If there is a single argument (as
n34+exception instance's :attr:`args` attribute.
51-is preferred), it is bound to the :attr:`message` attribute.
52
53User code can raise built-in exceptions.  This can be used to test an exception
54handler or to report an error condition "just like" the situation in which the
55interpreter raises the same exception; but beware that there is nothing to
56prevent user code from raising an inappropriate error.
57
58The built-in exception classes can be sub-classed to define new exceptions;
59programmers are encouraged to at least derive new exceptions from the
60:exc:`Exception` class and not :exc:`BaseException`.  More information on
n61-defining exceptions is available in the Python Tutorial (XXX reference:
n44+defining exceptions is available in the Python Tutorial under
62-../tut/tut.html) under the heading "User-defined Exceptions."
45+:ref:`tut-userexceptions`.
63
64The following exceptions are only used as base classes for other exceptions.
65
66
67.. exception:: BaseException
68
69   The base class for all built-in exceptions.  It is not meant to be directly
70   inherited by user-defined classes (for that use :exc:`Exception`).  If
71   :func:`str` or :func:`unicode` is called on an instance of this class, the
n72-   representation of the argument(s) to the instance are returned or the emptry
n55+   representation of the argument(s) to the instance are returned or the empty
73-   string when there were no arguments.  If only a single argument ipassed in, it
56+   string when there were no arguments.  All arguments are  stored in :attr:`args`
74-   is stored in the :attr:`message` attribute.  If more than one argument is passed
57+   as a tuple.
75-   in, :attr:`message` is set to the empty string.  These semantics are meant to
76-   reflect the fact that :attr:`message` is to store a text message explaining why
77-   the exception had been raised.  If more data needs to be attached to the
78-   exception, attach it through arbitrary attributes on the instance.  All
79-   arguments are also stored in :attr:`args` as a tuple, but it will eventually be
80-   deprecated and thus its use is discouraged.
81
82   .. versionadded:: 2.5
83
84
85.. exception:: Exception
86
87   All built-in, non-system-exiting exceptions are derived from this class.  All
88   user-defined exceptions should also be derived from this class.
142
143   .. index:: statement: assert
144
145   Raised when an :keyword:`assert` statement fails.
146
147
148.. exception:: AttributeError
149
n150-   Raised when an attribute reference or assignment fails.  (When an object does
n127+   Raised when an attribute reference (see :ref:`attribute-references`) or
151-   not support attribute references or attribute assignments at all,
128+   assignment fails.  (When an object does not support attribute references or
152-   :exc:`TypeError` is raised.)
129+   attribute assignments at all, :exc:`TypeError` is raised.)
153- 
154-   .. % xref to attribute reference?
155
156
157.. exception:: EOFError
158
159   Raised when one of the built-in functions (:func:`input` or :func:`raw_input`)
160   hits an end-of-file condition (EOF) without reading any data. (N.B.: the
n161-   :meth:`read` and :meth:`readline` methods of file objects return an empty string
n136+   :meth:`file.read` and :meth:`file.readline` methods return an empty string
162   when they hit EOF.)
n163- 
164-   .. % XXXJH xrefs here
165-   .. % XXXJH xrefs here
166
167
168.. exception:: FloatingPointError
169
170   Raised when a floating point operation fails.  This exception is always defined,
171   but can only be raised when Python is configured with the
172   :option:`--with-fpectl` option, or the :const:`WANT_SIGFPE_HANDLER` symbol is
173   defined in the :file:`pyconfig.h` file.
174
175
176.. exception:: GeneratorExit
177
n178-   Raise when a generator's :meth:`close` method is called. It directly inherits
n150+   Raise when a :term:`generator`\'s :meth:`close` method is called.  It
179-   from :exc:`Exception` instead of :exc:`StandardError` since it is technically
151+   directly inherits from :exc:`BaseException` instead of :exc:`StandardError` since
180-   not an error.
152+   it is technically not an error.
181
182   .. versionadded:: 2.5
183
n156+   .. versionchanged:: 2.6
157+      Changed to inherit from :exc:`BaseException`.
184
185.. exception:: IOError
186
187   Raised when an I/O operation (such as a :keyword:`print` statement, the built-in
188   :func:`open` function or a method of a file object) fails for an I/O-related
189   reason, e.g., "file not found" or "disk full".
190
n191-   .. % XXXJH xrefs here
192- 
193   This class is derived from :exc:`EnvironmentError`.  See the discussion above
194   for more information on exception instance attributes.
195
n168+   .. versionchanged:: 2.6
169+      Changed :exc:`socket.error` to use this as a base class.
170+ 
196
197.. exception:: ImportError
198
199   Raised when an :keyword:`import` statement fails to find the module definition
200   or when a ``from ... import`` fails to find a name that is to be imported.
n201- 
202-   .. % XXXJH xref to import statement?
203
204
205.. exception:: IndexError
206
207   Raised when a sequence subscript is out of range.  (Slice indices are silently
208   truncated to fall in the allowed range; if an index is not a plain integer,
209   :exc:`TypeError` is raised.)
210
n211-   .. % XXXJH xref to sequences
n184+   .. XXX xref to sequences
212
213
214.. exception:: KeyError
215
216   Raised when a mapping (dictionary) key is not found in the set of existing keys.
217
n218-   .. % XXXJH xref to mapping objects?
n191+   .. XXX xref to mapping objects?
219
220
221.. exception:: KeyboardInterrupt
222
223   Raised when the user hits the interrupt key (normally :kbd:`Control-C` or
224   :kbd:`Delete`).  During execution, a check for interrupts is made regularly.
225   Interrupts typed when a built-in function :func:`input` or :func:`raw_input` is
226   waiting for input also raise this exception. The exception inherits from
227   :exc:`BaseException` so as to not be accidentally caught by code that catches
228   :exc:`Exception` and thus prevent the interpreter from exiting.
n229- 
230-   .. % XXX(hylton) xrefs here
231
232   .. versionchanged:: 2.5
233      Changed to inherit from :exc:`BaseException`.
234
235
236.. exception:: MemoryError
237
238   Raised when an operation runs out of memory but the situation may still be
257   classes, abstract methods should raise this exception when they require derived
258   classes to override the method.
259
260   .. versionadded:: 1.5.2
261
262
263.. exception:: OSError
264
n265-   This class is derived from :exc:`EnvironmentError` and is used primarily as the
n236+   .. index:: module: errno
266-   :mod:`os` module's ``os.error`` exception. See :exc:`EnvironmentError` above for
267-   a description of the possible associated values.
268
n269-   .. % xref for os module
n238+   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.
245+ 
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.
270
271   .. versionadded:: 1.5.2
272
273
274.. exception:: OverflowError
275
276   Raised when the result of an arithmetic operation is too large to be
277   represented.  This cannot occur for long integers (which would rather raise
n278-   :exc:`MemoryError` than give up).  Because of the lack of standardization of
n257+   :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
279-   floating point exception handling in C, most floating point operations also
259+   of floating point exception handling in C, most floating point operations
280-   aren't checked.  For plain integers, all operations that can overflow are
260+   also aren't checked.
281-   checked except left shift, where typical applications prefer to drop bits than
282-   raise an exception.
283- 
284-   .. % XXXJH reference to long's and/or int's?
285
286
287.. exception:: ReferenceError
288
289   This exception is raised when a weak reference proxy, created by the
290   :func:`weakref.proxy` function, is used to access an attribute of the referent
291   after it has been garbage collected. For more information on weak references,
292   see the :mod:`weakref` module.
300   Raised when an error is detected that doesn't fall in any of the other
301   categories.  The associated value is a string indicating what precisely went
302   wrong.  (This exception is mostly a relic from a previous version of the
303   interpreter; it is not used very much any more.)
304
305
306.. exception:: StopIteration
307
n308-   Raised by an iterator's :meth:`next` method to signal that there are no further
n284+   Raised by an :term:`iterator`\'s :meth:`next` method to signal that there are
309-   values. This is derived from :exc:`Exception` rather than :exc:`StandardError`,
285+   no further values.  This is derived from :exc:`Exception` rather than
310-   since this is not considered an error in its normal application.
286+   :exc:`StandardError`, since this is not considered an error in its normal
287+   application.
311
312   .. versionadded:: 2.2
313
314
315.. exception:: SyntaxError
316
317   Raised when the parser encounters a syntax error.  This may occur in an
318   :keyword:`import` statement, in an :keyword:`exec` statement, in a call to the
319   built-in function :func:`eval` or :func:`input`, or when reading the initial
320   script or standard input (also interactively).
n321- 
322-   .. % XXXJH xref to these functions?
323
324   Instances of this class have attributes :attr:`filename`, :attr:`lineno`,
325   :attr:`offset` and :attr:`text` for easier access to the details.  :func:`str`
326   of the exception instance returns only the message.
327
328
329.. exception:: SystemError
330
343
344   This exception is raised by the :func:`sys.exit` function.  When it is not
345   handled, the Python interpreter exits; no stack traceback is printed.  If the
346   associated value is a plain integer, it specifies the system exit status (passed
347   to C's :cfunc:`exit` function); if it is ``None``, the exit status is zero; if
348   it has another type (such as a string), the object's value is printed and the
349   exit status is one.
350
n351-   .. % XXX(hylton) xref to module sys?
352- 
353   Instances have an attribute :attr:`code` which is set to the proposed exit
354   status or error message (defaulting to ``None``). Also, this exception derives
355   directly from :exc:`BaseException` and not :exc:`StandardError`, since it is not
356   technically an error.
357
358   A call to :func:`sys.exit` is translated into an exception so that clean-up
359   handlers (:keyword:`finally` clauses of :keyword:`try` statements) can be
360   executed, and so that a debugger can execute a script without running the risk
420
421.. exception:: ValueError
422
423   Raised when a built-in operation or function receives an argument that has the
424   right type but an inappropriate value, and the situation is not described by a
425   more precise exception such as :exc:`IndexError`.
426
427
n401+.. exception:: VMSError
402+ 
403+   Only available on VMS.  Raised when a VMS-specific error occurs.
404+ 
405+ 
428.. exception:: WindowsError
429
430   Raised when a Windows-specific error occurs or when the error number does not
431   correspond to an :cdata:`errno` value.  The :attr:`winerror` and
432   :attr:`strerror` values are created from the return values of the
433   :cfunc:`GetLastError` and :cfunc:`FormatMessage` functions from the Windows
434   Platform API. The :attr:`errno` value maps the :attr:`winerror` value to
435   corresponding ``errno.h`` values. This is a subclass of :exc:`OSError`.
497
498   Base class for warnings related to Unicode.
499
500   .. versionadded:: 2.5
501
502The class hierarchy for built-in exceptions is:
503
504
t505-.. XXX includefile ../../Lib/test/exception_hierarchy.txt
t483+.. literalinclude:: ../../Lib/test/exception_hierarchy.txt
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op