blob: bf7be21f68bd4feed4618f0035386e89ecfa519f [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 Brandlfbd1b222009-12-29 21:38:35 +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"
21indicating the detailed cause of the error. This may be a string or a tuple
22containing several items of information (e.g., an error code and a string
Benjamin Petersonb496bad2010-05-10 20:49:20 +000023explaining the code). The associated value is usually passed to the exception
24class's constructor. If the exception class is derived from the standard root
25class :exc:`BaseException`, the associated value is present as the exception
26instance's :attr:`args` attribute.
Georg Brandl116aa622007-08-15 14:28:22 +000027
28User code can raise built-in exceptions. This can be used to test an exception
29handler or to report an error condition "just like" the situation in which the
30interpreter raises the same exception; but beware that there is nothing to
31prevent user code from raising an inappropriate error.
32
33The built-in exception classes can be sub-classed to define new exceptions;
34programmers are encouraged to at least derive new exceptions from the
35:exc:`Exception` class and not :exc:`BaseException`. More information on
36defining exceptions is available in the Python Tutorial under
37:ref:`tut-userexceptions`.
38
Georg Brandlfbd1b222009-12-29 21:38:35 +000039The following exceptions are used mostly as base classes for other exceptions.
Georg Brandl116aa622007-08-15 14:28:22 +000040
Georg Brandl02c30562007-09-07 17:52:53 +000041.. XXX document with_traceback()
Georg Brandl116aa622007-08-15 14:28:22 +000042
43.. exception:: BaseException
44
45 The base class for all built-in exceptions. It is not meant to be directly
46 inherited by user-defined classes (for that use :exc:`Exception`). If
Ezio Melotti985e24d2009-09-13 07:54:02 +000047 :func:`bytes` or :func:`str` is called on an instance of this class, the
Georg Brandlae2dbe22009-03-13 19:04:40 +000048 representation of the argument(s) to the instance are returned or the empty
Georg Brandl116aa622007-08-15 14:28:22 +000049 string when there were no arguments. All arguments are stored in :attr:`args`
50 as a tuple.
51
Georg Brandl116aa622007-08-15 14:28:22 +000052
53.. exception:: Exception
54
55 All built-in, non-system-exiting exceptions are derived from this class. All
56 user-defined exceptions should also be derived from this class.
57
Georg Brandl116aa622007-08-15 14:28:22 +000058
59.. exception:: ArithmeticError
60
61 The base class for those built-in exceptions that are raised for various
62 arithmetic errors: :exc:`OverflowError`, :exc:`ZeroDivisionError`,
63 :exc:`FloatingPointError`.
64
65
Georg Brandl0bdfbfa2010-12-18 17:51:28 +000066.. exception:: BufferError
67
68 Raised when a :ref:`buffer <bufferobjects>` related operation cannot be
69 performed.
70
71
Georg Brandl116aa622007-08-15 14:28:22 +000072.. exception:: LookupError
73
Benjamin Petersonfa0d7032009-06-01 22:42:33 +000074 The base class for the exceptions that are raised when a key or index used on
75 a mapping or sequence is invalid: :exc:`IndexError`, :exc:`KeyError`. This
76 can be raised directly by :func:`codecs.lookup`.
Georg Brandl116aa622007-08-15 14:28:22 +000077
78
79.. exception:: EnvironmentError
80
81 The base class for exceptions that can occur outside the Python system:
82 :exc:`IOError`, :exc:`OSError`. When exceptions of this type are created with a
83 2-tuple, the first item is available on the instance's :attr:`errno` attribute
84 (it is assumed to be an error number), and the second item is available on the
85 :attr:`strerror` attribute (it is usually the associated error message). The
86 tuple itself is also available on the :attr:`args` attribute.
87
Georg Brandl116aa622007-08-15 14:28:22 +000088 When an :exc:`EnvironmentError` exception is instantiated with a 3-tuple, the
89 first two items are available as above, while the third item is available on the
90 :attr:`filename` attribute. However, for backwards compatibility, the
91 :attr:`args` attribute contains only a 2-tuple of the first two constructor
92 arguments.
93
94 The :attr:`filename` attribute is ``None`` when this exception is created with
95 other than 3 arguments. The :attr:`errno` and :attr:`strerror` attributes are
96 also ``None`` when the instance was created with other than 2 or 3 arguments.
97 In this last case, :attr:`args` contains the verbatim constructor arguments as a
98 tuple.
99
Georg Brandl116aa622007-08-15 14:28:22 +0000100
Georg Brandlfbd1b222009-12-29 21:38:35 +0000101The following exceptions are the exceptions that are usually raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000102
103.. exception:: AssertionError
104
105 .. index:: statement: assert
106
107 Raised when an :keyword:`assert` statement fails.
108
109
110.. exception:: AttributeError
111
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000112 Raised when an attribute reference (see :ref:`attribute-references`) or
113 assignment fails. (When an object does not support attribute references or
114 attribute assignments at all, :exc:`TypeError` is raised.)
Georg Brandl116aa622007-08-15 14:28:22 +0000115
116
117.. exception:: EOFError
118
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000119 Raised when one of the built-in functions (:func:`input` or :func:`raw_input`)
120 hits an end-of-file condition (EOF) without reading any data. (N.B.: the
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000121 :meth:`file.read` and :meth:`file.readline` methods return an empty string
122 when they hit EOF.)
Georg Brandl116aa622007-08-15 14:28:22 +0000123
124
125.. exception:: FloatingPointError
126
127 Raised when a floating point operation fails. This exception is always defined,
128 but can only be raised when Python is configured with the
Éric Araujo713d3032010-11-18 16:38:46 +0000129 ``--with-fpectl`` option, or the :const:`WANT_SIGFPE_HANDLER` symbol is
Georg Brandl116aa622007-08-15 14:28:22 +0000130 defined in the :file:`pyconfig.h` file.
131
132
133.. exception:: GeneratorExit
134
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000135 Raise when a :term:`generator`\'s :meth:`close` method is called. It
136 directly inherits from :exc:`BaseException` instead of :exc:`Exception` since
137 it is technically not an error.
Georg Brandl116aa622007-08-15 14:28:22 +0000138
Georg Brandl116aa622007-08-15 14:28:22 +0000139
140.. exception:: IOError
141
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000142 Raised when an I/O operation (such as the built-in :func:`print` or
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000143 :func:`open` functions or a method of a :term:`file object`) fails for an
144 I/O-related reason, e.g., "file not found" or "disk full".
Georg Brandl116aa622007-08-15 14:28:22 +0000145
Georg Brandl116aa622007-08-15 14:28:22 +0000146 This class is derived from :exc:`EnvironmentError`. See the discussion above
147 for more information on exception instance attributes.
148
149
150.. exception:: ImportError
151
152 Raised when an :keyword:`import` statement fails to find the module definition
153 or when a ``from ... import`` fails to find a name that is to be imported.
154
Georg Brandl116aa622007-08-15 14:28:22 +0000155
156.. exception:: IndexError
157
Georg Brandl95817b32008-05-11 14:30:18 +0000158 Raised when a sequence subscript is out of range. (Slice indices are
159 silently truncated to fall in the allowed range; if an index is not an
160 integer, :exc:`TypeError` is raised.)
Georg Brandl116aa622007-08-15 14:28:22 +0000161
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000162 .. XXX xref to sequences
Georg Brandl116aa622007-08-15 14:28:22 +0000163
164
165.. exception:: KeyError
166
167 Raised when a mapping (dictionary) key is not found in the set of existing keys.
168
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000169 .. XXX xref to mapping objects?
Georg Brandl116aa622007-08-15 14:28:22 +0000170
171
172.. exception:: KeyboardInterrupt
173
174 Raised when the user hits the interrupt key (normally :kbd:`Control-C` or
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000175 :kbd:`Delete`). During execution, a check for interrupts is made
176 regularly. The exception inherits from :exc:`BaseException` so as to not be
177 accidentally caught by code that catches :exc:`Exception` and thus prevent
178 the interpreter from exiting.
Georg Brandl116aa622007-08-15 14:28:22 +0000179
Georg Brandl116aa622007-08-15 14:28:22 +0000180
181.. exception:: MemoryError
182
183 Raised when an operation runs out of memory but the situation may still be
184 rescued (by deleting some objects). The associated value is a string indicating
185 what kind of (internal) operation ran out of memory. Note that because of the
Georg Brandl60203b42010-10-06 10:11:56 +0000186 underlying memory management architecture (C's :c:func:`malloc` function), the
Georg Brandl116aa622007-08-15 14:28:22 +0000187 interpreter may not always be able to completely recover from this situation; it
188 nevertheless raises an exception so that a stack traceback can be printed, in
189 case a run-away program was the cause.
190
191
192.. exception:: NameError
193
194 Raised when a local or global name is not found. This applies only to
195 unqualified names. The associated value is an error message that includes the
196 name that could not be found.
197
198
199.. exception:: NotImplementedError
200
201 This exception is derived from :exc:`RuntimeError`. In user defined base
202 classes, abstract methods should raise this exception when they require derived
203 classes to override the method.
204
Georg Brandl116aa622007-08-15 14:28:22 +0000205
206.. exception:: OSError
207
Christian Heimesa62da1d2008-01-12 19:39:10 +0000208 .. index:: module: errno
209
210 This exception is derived from :exc:`EnvironmentError`. It is raised when a
211 function returns a system-related error (not for illegal argument types or
212 other incidental errors). The :attr:`errno` attribute is a numeric error
Georg Brandl60203b42010-10-06 10:11:56 +0000213 code from :c:data:`errno`, and the :attr:`strerror` attribute is the
214 corresponding string, as would be printed by the C function :c:func:`perror`.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000215 See the module :mod:`errno`, which contains names for the error codes defined
216 by the underlying operating system.
217
218 For exceptions that involve a file system path (such as :func:`chdir` or
219 :func:`unlink`), the exception instance will contain a third attribute,
220 :attr:`filename`, which is the file name passed to the function.
Georg Brandl116aa622007-08-15 14:28:22 +0000221
Georg Brandl116aa622007-08-15 14:28:22 +0000222
223.. exception:: OverflowError
224
225 Raised when the result of an arithmetic operation is too large to be
Georg Brandlba956ae2007-11-29 17:24:34 +0000226 represented. This cannot occur for integers (which would rather raise
Georg Brandl116aa622007-08-15 14:28:22 +0000227 :exc:`MemoryError` than give up). Because of the lack of standardization of
228 floating point exception handling in C, most floating point operations also
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000229 aren't checked.
Georg Brandl116aa622007-08-15 14:28:22 +0000230
231
232.. exception:: ReferenceError
233
234 This exception is raised when a weak reference proxy, created by the
235 :func:`weakref.proxy` function, is used to access an attribute of the referent
236 after it has been garbage collected. For more information on weak references,
237 see the :mod:`weakref` module.
238
Georg Brandl116aa622007-08-15 14:28:22 +0000239
240.. exception:: RuntimeError
241
242 Raised when an error is detected that doesn't fall in any of the other
243 categories. The associated value is a string indicating what precisely went
244 wrong. (This exception is mostly a relic from a previous version of the
245 interpreter; it is not used very much any more.)
246
247
248.. exception:: StopIteration
249
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000250 Raised by built-in function :func:`next` and an :term:`iterator`\'s
251 :meth:`__next__` method to signal that there are no further values.
Georg Brandl116aa622007-08-15 14:28:22 +0000252
Georg Brandl116aa622007-08-15 14:28:22 +0000253
254.. exception:: SyntaxError
255
256 Raised when the parser encounters a syntax error. This may occur in an
257 :keyword:`import` statement, in a call to the built-in functions :func:`exec`
258 or :func:`eval`, or when reading the initial script or standard input
259 (also interactively).
260
Georg Brandl116aa622007-08-15 14:28:22 +0000261 Instances of this class have attributes :attr:`filename`, :attr:`lineno`,
262 :attr:`offset` and :attr:`text` for easier access to the details. :func:`str`
263 of the exception instance returns only the message.
264
265
Georg Brandl0bdfbfa2010-12-18 17:51:28 +0000266.. exception:: IndentationError
267
268 Base class for syntax errors related to incorrect indentation. This is a
269 subclass of :exc:`SyntaxError`.
270
271
272.. exception:: TabError
273
274 Raised when indentation contains an inconsistent use of tabs and spaces.
275 This is a subclass of :exc:`IndentationError`.
276
277
Georg Brandl116aa622007-08-15 14:28:22 +0000278.. exception:: SystemError
279
280 Raised when the interpreter finds an internal error, but the situation does not
281 look so serious to cause it to abandon all hope. The associated value is a
282 string indicating what went wrong (in low-level terms).
283
284 You should report this to the author or maintainer of your Python interpreter.
285 Be sure to report the version of the Python interpreter (``sys.version``; it is
286 also printed at the start of an interactive Python session), the exact error
287 message (the exception's associated value) and if possible the source of the
288 program that triggered the error.
289
290
291.. exception:: SystemExit
292
293 This exception is raised by the :func:`sys.exit` function. When it is not
294 handled, the Python interpreter exits; no stack traceback is printed. If the
Georg Brandl95817b32008-05-11 14:30:18 +0000295 associated value is an integer, it specifies the system exit status (passed
Georg Brandl60203b42010-10-06 10:11:56 +0000296 to C's :c:func:`exit` function); if it is ``None``, the exit status is zero;
Georg Brandl95817b32008-05-11 14:30:18 +0000297 if it has another type (such as a string), the object's value is printed and
298 the exit status is one.
Georg Brandl116aa622007-08-15 14:28:22 +0000299
Georg Brandl116aa622007-08-15 14:28:22 +0000300 Instances have an attribute :attr:`code` which is set to the proposed exit
301 status or error message (defaulting to ``None``). Also, this exception derives
302 directly from :exc:`BaseException` and not :exc:`Exception`, since it is not
303 technically an error.
304
305 A call to :func:`sys.exit` is translated into an exception so that clean-up
306 handlers (:keyword:`finally` clauses of :keyword:`try` statements) can be
307 executed, and so that a debugger can execute a script without running the risk
308 of losing control. The :func:`os._exit` function can be used if it is
309 absolutely positively necessary to exit immediately (for example, in the child
310 process after a call to :func:`fork`).
311
312 The exception inherits from :exc:`BaseException` instead of :exc:`Exception` so
313 that it is not accidentally caught by code that catches :exc:`Exception`. This
314 allows the exception to properly propagate up and cause the interpreter to exit.
315
Georg Brandl116aa622007-08-15 14:28:22 +0000316
317.. exception:: TypeError
318
319 Raised when an operation or function is applied to an object of inappropriate
320 type. The associated value is a string giving details about the type mismatch.
321
322
323.. exception:: UnboundLocalError
324
325 Raised when a reference is made to a local variable in a function or method, but
326 no value has been bound to that variable. This is a subclass of
327 :exc:`NameError`.
328
Georg Brandl116aa622007-08-15 14:28:22 +0000329
330.. exception:: UnicodeError
331
332 Raised when a Unicode-related encoding or decoding error occurs. It is a
333 subclass of :exc:`ValueError`.
334
Georg Brandl116aa622007-08-15 14:28:22 +0000335
336.. exception:: UnicodeEncodeError
337
338 Raised when a Unicode-related error occurs during encoding. It is a subclass of
339 :exc:`UnicodeError`.
340
Georg Brandl116aa622007-08-15 14:28:22 +0000341
342.. exception:: UnicodeDecodeError
343
344 Raised when a Unicode-related error occurs during decoding. It is a subclass of
345 :exc:`UnicodeError`.
346
Georg Brandl116aa622007-08-15 14:28:22 +0000347
348.. exception:: UnicodeTranslateError
349
350 Raised when a Unicode-related error occurs during translating. It is a subclass
351 of :exc:`UnicodeError`.
352
Georg Brandl116aa622007-08-15 14:28:22 +0000353
354.. exception:: ValueError
355
356 Raised when a built-in operation or function receives an argument that has the
357 right type but an inappropriate value, and the situation is not described by a
358 more precise exception such as :exc:`IndexError`.
359
360
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000361.. exception:: VMSError
362
363 Only available on VMS. Raised when a VMS-specific error occurs.
364
365
Georg Brandl116aa622007-08-15 14:28:22 +0000366.. exception:: WindowsError
367
368 Raised when a Windows-specific error occurs or when the error number does not
Georg Brandl60203b42010-10-06 10:11:56 +0000369 correspond to an :c:data:`errno` value. The :attr:`winerror` and
Georg Brandl116aa622007-08-15 14:28:22 +0000370 :attr:`strerror` values are created from the return values of the
Georg Brandl60203b42010-10-06 10:11:56 +0000371 :c:func:`GetLastError` and :c:func:`FormatMessage` functions from the Windows
Georg Brandl116aa622007-08-15 14:28:22 +0000372 Platform API. The :attr:`errno` value maps the :attr:`winerror` value to
373 corresponding ``errno.h`` values. This is a subclass of :exc:`OSError`.
374
Georg Brandl116aa622007-08-15 14:28:22 +0000375
376.. exception:: ZeroDivisionError
377
378 Raised when the second argument of a division or modulo operation is zero. The
379 associated value is a string indicating the type of the operands and the
380 operation.
381
Georg Brandlfbd1b222009-12-29 21:38:35 +0000382
Georg Brandl116aa622007-08-15 14:28:22 +0000383The following exceptions are used as warning categories; see the :mod:`warnings`
384module for more information.
385
Georg Brandl116aa622007-08-15 14:28:22 +0000386.. exception:: Warning
387
388 Base class for warning categories.
389
390
391.. exception:: UserWarning
392
393 Base class for warnings generated by user code.
394
395
396.. exception:: DeprecationWarning
397
398 Base class for warnings about deprecated features.
399
400
401.. exception:: PendingDeprecationWarning
402
403 Base class for warnings about features which will be deprecated in the future.
404
405
406.. exception:: SyntaxWarning
407
408 Base class for warnings about dubious syntax
409
410
411.. exception:: RuntimeWarning
412
413 Base class for warnings about dubious runtime behavior.
414
415
416.. exception:: FutureWarning
417
418 Base class for warnings about constructs that will change semantically in the
419 future.
420
421
422.. exception:: ImportWarning
423
424 Base class for warnings about probable mistakes in module imports.
425
Georg Brandl116aa622007-08-15 14:28:22 +0000426
427.. exception:: UnicodeWarning
428
429 Base class for warnings related to Unicode.
430
Georg Brandl08be72d2010-10-24 15:11:22 +0000431
Guido van Rossum98297ee2007-11-06 21:34:58 +0000432.. exception:: BytesWarning
Georg Brandl116aa622007-08-15 14:28:22 +0000433
Guido van Rossum98297ee2007-11-06 21:34:58 +0000434 Base class for warnings related to :class:`bytes` and :class:`buffer`.
435
Georg Brandl08be72d2010-10-24 15:11:22 +0000436
437.. exception:: ResourceWarning
438
439 Base class for warnings related to resource usage.
440
441 .. versionadded:: 3.2
442
443
444
Alexandre Vassalottic22c6f22009-07-21 00:51:58 +0000445Exception hierarchy
446-------------------
Guido van Rossum98297ee2007-11-06 21:34:58 +0000447
448The class hierarchy for built-in exceptions is:
Georg Brandl116aa622007-08-15 14:28:22 +0000449
450.. literalinclude:: ../../Lib/test/exception_hierarchy.txt