blob: 7ecfbca09121b7ca652faa4a2c52685f6ff7ef54 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. _bltin-exceptions:
2
3Built-in Exceptions
4===================
5
Georg Brandl116aa622007-08-15 14:28:22 +00006.. index::
7 statement: try
8 statement: except
9
Georg Brandl8ffe0bc2010-10-06 07:17:29 +000010In Python, all exceptions must be instances of a class that derives from
11:class:`BaseException`. In a :keyword:`try` statement with an :keyword:`except`
Georg Brandl116aa622007-08-15 14:28:22 +000012clause that mentions a particular class, that clause also handles any exception
13classes derived from that class (but not exception classes from which *it* is
14derived). Two exception classes that are not related via subclassing are never
15equivalent, even if they have the same name.
16
17.. index:: statement: raise
18
19The built-in exceptions listed below can be generated by the interpreter or
20built-in functions. Except where mentioned, they have an "associated value"
Georg Brandlec78b8b2011-01-09 07:59:02 +000021indicating the detailed cause of the error. This may be a string or a tuple of
22several items of information (e.g., an error code and a string explaining the
23code). The associated value is usually passed as arguments to the exception
24class's constructor.
Georg Brandl116aa622007-08-15 14:28:22 +000025
26User code can raise built-in exceptions. This can be used to test an exception
27handler or to report an error condition "just like" the situation in which the
28interpreter raises the same exception; but beware that there is nothing to
29prevent user code from raising an inappropriate error.
30
31The built-in exception classes can be sub-classed to define new exceptions;
32programmers are encouraged to at least derive new exceptions from the
33:exc:`Exception` class and not :exc:`BaseException`. More information on
34defining exceptions is available in the Python Tutorial under
35:ref:`tut-userexceptions`.
36
Georg Brandl8ffe0bc2010-10-06 07:17:29 +000037The following exceptions are used mostly as base classes for other exceptions.
Georg Brandl116aa622007-08-15 14:28:22 +000038
Georg Brandl116aa622007-08-15 14:28:22 +000039.. exception:: BaseException
40
41 The base class for all built-in exceptions. It is not meant to be directly
Georg Brandlec78b8b2011-01-09 07:59:02 +000042 inherited by user-defined classes (for that, use :exc:`Exception`). If
Ezio Melotti713e0422009-09-13 08:13:21 +000043 :func:`bytes` or :func:`str` is called on an instance of this class, the
Georg Brandlec78b8b2011-01-09 07:59:02 +000044 representation of the argument(s) to the instance are returned, or the empty
45 string when there were no arguments.
46
47 .. attribute:: args
48
49 The tuple of arguments given to the exception constructor. Some built-in
50 exceptions (like :exc:`IOError`) expect a certain number of arguments and
51 assign a special meaning to the elements of this tuple, while others are
52 usually called only with a single string giving an error message.
53
54 .. method:: with_traceback(tb)
55
56 This method sets *tb* as the new traceback for the exception and returns
57 the exception object. It is usually used in exception handling code like
58 this::
59
60 try:
61 ...
62 except SomeException:
63 tb = sys.exc_info()[2]
64 raise OtherException(...).with_traceback(tb)
Georg Brandl116aa622007-08-15 14:28:22 +000065
Georg Brandl116aa622007-08-15 14:28:22 +000066
67.. exception:: Exception
68
69 All built-in, non-system-exiting exceptions are derived from this class. All
70 user-defined exceptions should also be derived from this class.
71
Georg Brandl116aa622007-08-15 14:28:22 +000072
73.. exception:: ArithmeticError
74
75 The base class for those built-in exceptions that are raised for various
76 arithmetic errors: :exc:`OverflowError`, :exc:`ZeroDivisionError`,
77 :exc:`FloatingPointError`.
78
79
80.. exception:: LookupError
81
Benjamin Petersonfa0d7032009-06-01 22:42:33 +000082 The base class for the exceptions that are raised when a key or index used on
83 a mapping or sequence is invalid: :exc:`IndexError`, :exc:`KeyError`. This
84 can be raised directly by :func:`codecs.lookup`.
Georg Brandl116aa622007-08-15 14:28:22 +000085
86
87.. exception:: EnvironmentError
88
89 The base class for exceptions that can occur outside the Python system:
90 :exc:`IOError`, :exc:`OSError`. When exceptions of this type are created with a
91 2-tuple, the first item is available on the instance's :attr:`errno` attribute
92 (it is assumed to be an error number), and the second item is available on the
93 :attr:`strerror` attribute (it is usually the associated error message). The
94 tuple itself is also available on the :attr:`args` attribute.
95
Georg Brandl116aa622007-08-15 14:28:22 +000096 When an :exc:`EnvironmentError` exception is instantiated with a 3-tuple, the
97 first two items are available as above, while the third item is available on the
98 :attr:`filename` attribute. However, for backwards compatibility, the
99 :attr:`args` attribute contains only a 2-tuple of the first two constructor
100 arguments.
101
102 The :attr:`filename` attribute is ``None`` when this exception is created with
103 other than 3 arguments. The :attr:`errno` and :attr:`strerror` attributes are
104 also ``None`` when the instance was created with other than 2 or 3 arguments.
105 In this last case, :attr:`args` contains the verbatim constructor arguments as a
106 tuple.
107
Georg Brandl116aa622007-08-15 14:28:22 +0000108
Georg Brandl8ffe0bc2010-10-06 07:17:29 +0000109The following exceptions are the exceptions that are usually raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000110
111.. exception:: AssertionError
112
113 .. index:: statement: assert
114
115 Raised when an :keyword:`assert` statement fails.
116
117
118.. exception:: AttributeError
119
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000120 Raised when an attribute reference (see :ref:`attribute-references`) or
121 assignment fails. (When an object does not support attribute references or
122 attribute assignments at all, :exc:`TypeError` is raised.)
Georg Brandl116aa622007-08-15 14:28:22 +0000123
124
125.. exception:: EOFError
126
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000127 Raised when one of the built-in functions (:func:`input` or :func:`raw_input`)
128 hits an end-of-file condition (EOF) without reading any data. (N.B.: the
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000129 :meth:`file.read` and :meth:`file.readline` methods return an empty string
130 when they hit EOF.)
Georg Brandl116aa622007-08-15 14:28:22 +0000131
132
133.. exception:: FloatingPointError
134
135 Raised when a floating point operation fails. This exception is always defined,
136 but can only be raised when Python is configured with the
Éric Araujo3efdf062010-12-16 03:16:29 +0000137 ``--with-fpectl`` option, or the :const:`WANT_SIGFPE_HANDLER` symbol is
Georg Brandl116aa622007-08-15 14:28:22 +0000138 defined in the :file:`pyconfig.h` file.
139
140
141.. exception:: GeneratorExit
142
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000143 Raise when a :term:`generator`\'s :meth:`close` method is called. It
144 directly inherits from :exc:`BaseException` instead of :exc:`Exception` since
145 it is technically not an error.
Georg Brandl116aa622007-08-15 14:28:22 +0000146
Georg Brandl116aa622007-08-15 14:28:22 +0000147
148.. exception:: IOError
149
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000150 Raised when an I/O operation (such as the built-in :func:`print` or
Antoine Pitrou25d535e2010-09-15 11:25:11 +0000151 :func:`open` functions or a method of a :term:`file object`) fails for an
152 I/O-related reason, e.g., "file not found" or "disk full".
Georg Brandl116aa622007-08-15 14:28:22 +0000153
Georg Brandl116aa622007-08-15 14:28:22 +0000154 This class is derived from :exc:`EnvironmentError`. See the discussion above
155 for more information on exception instance attributes.
156
157
158.. exception:: ImportError
159
160 Raised when an :keyword:`import` statement fails to find the module definition
161 or when a ``from ... import`` fails to find a name that is to be imported.
162
Georg Brandl116aa622007-08-15 14:28:22 +0000163
164.. exception:: IndexError
165
Georg Brandl95817b32008-05-11 14:30:18 +0000166 Raised when a sequence subscript is out of range. (Slice indices are
167 silently truncated to fall in the allowed range; if an index is not an
168 integer, :exc:`TypeError` is raised.)
Georg Brandl116aa622007-08-15 14:28:22 +0000169
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000170 .. XXX xref to sequences
Georg Brandl116aa622007-08-15 14:28:22 +0000171
172
173.. exception:: KeyError
174
175 Raised when a mapping (dictionary) key is not found in the set of existing keys.
176
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000177 .. XXX xref to mapping objects?
Georg Brandl116aa622007-08-15 14:28:22 +0000178
179
180.. exception:: KeyboardInterrupt
181
182 Raised when the user hits the interrupt key (normally :kbd:`Control-C` or
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000183 :kbd:`Delete`). During execution, a check for interrupts is made
184 regularly. The exception inherits from :exc:`BaseException` so as to not be
185 accidentally caught by code that catches :exc:`Exception` and thus prevent
186 the interpreter from exiting.
Georg Brandl116aa622007-08-15 14:28:22 +0000187
Georg Brandl116aa622007-08-15 14:28:22 +0000188
189.. exception:: MemoryError
190
191 Raised when an operation runs out of memory but the situation may still be
192 rescued (by deleting some objects). The associated value is a string indicating
193 what kind of (internal) operation ran out of memory. Note that because of the
194 underlying memory management architecture (C's :cfunc:`malloc` function), the
195 interpreter may not always be able to completely recover from this situation; it
196 nevertheless raises an exception so that a stack traceback can be printed, in
197 case a run-away program was the cause.
198
199
200.. exception:: NameError
201
202 Raised when a local or global name is not found. This applies only to
203 unqualified names. The associated value is an error message that includes the
204 name that could not be found.
205
206
207.. exception:: NotImplementedError
208
209 This exception is derived from :exc:`RuntimeError`. In user defined base
210 classes, abstract methods should raise this exception when they require derived
211 classes to override the method.
212
Georg Brandl116aa622007-08-15 14:28:22 +0000213
214.. exception:: OSError
215
Christian Heimesa62da1d2008-01-12 19:39:10 +0000216 .. index:: module: errno
217
218 This exception is derived from :exc:`EnvironmentError`. It is raised when a
219 function returns a system-related error (not for illegal argument types or
220 other incidental errors). The :attr:`errno` attribute is a numeric error
221 code from :cdata:`errno`, and the :attr:`strerror` attribute is the
222 corresponding string, as would be printed by the C function :cfunc:`perror`.
223 See the module :mod:`errno`, which contains names for the error codes defined
224 by the underlying operating system.
225
226 For exceptions that involve a file system path (such as :func:`chdir` or
227 :func:`unlink`), the exception instance will contain a third attribute,
228 :attr:`filename`, which is the file name passed to the function.
Georg Brandl116aa622007-08-15 14:28:22 +0000229
Georg Brandl116aa622007-08-15 14:28:22 +0000230
231.. exception:: OverflowError
232
233 Raised when the result of an arithmetic operation is too large to be
Georg Brandlba956ae2007-11-29 17:24:34 +0000234 represented. This cannot occur for integers (which would rather raise
Georg Brandl116aa622007-08-15 14:28:22 +0000235 :exc:`MemoryError` than give up). Because of the lack of standardization of
236 floating point exception handling in C, most floating point operations also
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000237 aren't checked.
Georg Brandl116aa622007-08-15 14:28:22 +0000238
239
240.. exception:: ReferenceError
241
242 This exception is raised when a weak reference proxy, created by the
243 :func:`weakref.proxy` function, is used to access an attribute of the referent
244 after it has been garbage collected. For more information on weak references,
245 see the :mod:`weakref` module.
246
Georg Brandl116aa622007-08-15 14:28:22 +0000247
248.. exception:: RuntimeError
249
250 Raised when an error is detected that doesn't fall in any of the other
251 categories. The associated value is a string indicating what precisely went
252 wrong. (This exception is mostly a relic from a previous version of the
253 interpreter; it is not used very much any more.)
254
255
256.. exception:: StopIteration
257
Georg Brandl9afde1c2007-11-01 20:32:30 +0000258 Raised by builtin :func:`next` and an :term:`iterator`\'s :meth:`__next__`
259 method to signal that there are no further values.
Georg Brandl116aa622007-08-15 14:28:22 +0000260
Georg Brandl116aa622007-08-15 14:28:22 +0000261
262.. exception:: SyntaxError
263
264 Raised when the parser encounters a syntax error. This may occur in an
265 :keyword:`import` statement, in a call to the built-in functions :func:`exec`
266 or :func:`eval`, or when reading the initial script or standard input
267 (also interactively).
268
Georg Brandl116aa622007-08-15 14:28:22 +0000269 Instances of this class have attributes :attr:`filename`, :attr:`lineno`,
270 :attr:`offset` and :attr:`text` for easier access to the details. :func:`str`
271 of the exception instance returns only the message.
272
273
274.. exception:: SystemError
275
276 Raised when the interpreter finds an internal error, but the situation does not
277 look so serious to cause it to abandon all hope. The associated value is a
278 string indicating what went wrong (in low-level terms).
279
280 You should report this to the author or maintainer of your Python interpreter.
281 Be sure to report the version of the Python interpreter (``sys.version``; it is
282 also printed at the start of an interactive Python session), the exact error
283 message (the exception's associated value) and if possible the source of the
284 program that triggered the error.
285
286
287.. exception:: SystemExit
288
289 This exception is raised by the :func:`sys.exit` function. When it is not
290 handled, the Python interpreter exits; no stack traceback is printed. If the
Georg Brandl95817b32008-05-11 14:30:18 +0000291 associated value is an integer, it specifies the system exit status (passed
292 to C's :cfunc:`exit` function); if it is ``None``, the exit status is zero;
293 if it has another type (such as a string), the object's value is printed and
294 the exit status is one.
Georg Brandl116aa622007-08-15 14:28:22 +0000295
Georg Brandl116aa622007-08-15 14:28:22 +0000296 Instances have an attribute :attr:`code` which is set to the proposed exit
297 status or error message (defaulting to ``None``). Also, this exception derives
298 directly from :exc:`BaseException` and not :exc:`Exception`, since it is not
299 technically an error.
300
301 A call to :func:`sys.exit` is translated into an exception so that clean-up
302 handlers (:keyword:`finally` clauses of :keyword:`try` statements) can be
303 executed, and so that a debugger can execute a script without running the risk
304 of losing control. The :func:`os._exit` function can be used if it is
305 absolutely positively necessary to exit immediately (for example, in the child
306 process after a call to :func:`fork`).
307
308 The exception inherits from :exc:`BaseException` instead of :exc:`Exception` so
309 that it is not accidentally caught by code that catches :exc:`Exception`. This
310 allows the exception to properly propagate up and cause the interpreter to exit.
311
Georg Brandl116aa622007-08-15 14:28:22 +0000312
313.. exception:: TypeError
314
315 Raised when an operation or function is applied to an object of inappropriate
316 type. The associated value is a string giving details about the type mismatch.
317
318
319.. exception:: UnboundLocalError
320
321 Raised when a reference is made to a local variable in a function or method, but
322 no value has been bound to that variable. This is a subclass of
323 :exc:`NameError`.
324
Georg Brandl116aa622007-08-15 14:28:22 +0000325
326.. exception:: UnicodeError
327
328 Raised when a Unicode-related encoding or decoding error occurs. It is a
329 subclass of :exc:`ValueError`.
330
Georg Brandl116aa622007-08-15 14:28:22 +0000331
332.. exception:: UnicodeEncodeError
333
334 Raised when a Unicode-related error occurs during encoding. It is a subclass of
335 :exc:`UnicodeError`.
336
Georg Brandl116aa622007-08-15 14:28:22 +0000337
338.. exception:: UnicodeDecodeError
339
340 Raised when a Unicode-related error occurs during decoding. It is a subclass of
341 :exc:`UnicodeError`.
342
Georg Brandl116aa622007-08-15 14:28:22 +0000343
344.. exception:: UnicodeTranslateError
345
346 Raised when a Unicode-related error occurs during translating. It is a subclass
347 of :exc:`UnicodeError`.
348
Georg Brandl116aa622007-08-15 14:28:22 +0000349
350.. exception:: ValueError
351
352 Raised when a built-in operation or function receives an argument that has the
353 right type but an inappropriate value, and the situation is not described by a
354 more precise exception such as :exc:`IndexError`.
355
356
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000357.. exception:: VMSError
358
359 Only available on VMS. Raised when a VMS-specific error occurs.
360
361
Georg Brandl116aa622007-08-15 14:28:22 +0000362.. exception:: WindowsError
363
364 Raised when a Windows-specific error occurs or when the error number does not
365 correspond to an :cdata:`errno` value. The :attr:`winerror` and
366 :attr:`strerror` values are created from the return values of the
367 :cfunc:`GetLastError` and :cfunc:`FormatMessage` functions from the Windows
368 Platform API. The :attr:`errno` value maps the :attr:`winerror` value to
369 corresponding ``errno.h`` values. This is a subclass of :exc:`OSError`.
370
Georg Brandl116aa622007-08-15 14:28:22 +0000371
372.. exception:: ZeroDivisionError
373
374 Raised when the second argument of a division or modulo operation is zero. The
375 associated value is a string indicating the type of the operands and the
376 operation.
377
Georg Brandl8ffe0bc2010-10-06 07:17:29 +0000378
Georg Brandl116aa622007-08-15 14:28:22 +0000379The following exceptions are used as warning categories; see the :mod:`warnings`
380module for more information.
381
Georg Brandl116aa622007-08-15 14:28:22 +0000382.. exception:: Warning
383
384 Base class for warning categories.
385
386
387.. exception:: UserWarning
388
389 Base class for warnings generated by user code.
390
391
392.. exception:: DeprecationWarning
393
394 Base class for warnings about deprecated features.
395
396
397.. exception:: PendingDeprecationWarning
398
399 Base class for warnings about features which will be deprecated in the future.
400
401
402.. exception:: SyntaxWarning
403
404 Base class for warnings about dubious syntax
405
406
407.. exception:: RuntimeWarning
408
409 Base class for warnings about dubious runtime behavior.
410
411
412.. exception:: FutureWarning
413
414 Base class for warnings about constructs that will change semantically in the
415 future.
416
417
418.. exception:: ImportWarning
419
420 Base class for warnings about probable mistakes in module imports.
421
Georg Brandl116aa622007-08-15 14:28:22 +0000422
423.. exception:: UnicodeWarning
424
425 Base class for warnings related to Unicode.
426
Guido van Rossum98297ee2007-11-06 21:34:58 +0000427.. exception:: BytesWarning
Georg Brandl116aa622007-08-15 14:28:22 +0000428
Guido van Rossum98297ee2007-11-06 21:34:58 +0000429 Base class for warnings related to :class:`bytes` and :class:`buffer`.
430
R. David Murrayba426142009-07-21 14:29:59 +0000431Exception hierarchy
432-------------------
Guido van Rossum98297ee2007-11-06 21:34:58 +0000433
434The class hierarchy for built-in exceptions is:
Georg Brandl116aa622007-08-15 14:28:22 +0000435
436.. literalinclude:: ../../Lib/test/exception_hierarchy.txt