blob: 528febd031fdaead18be3956dd8c1e775c822a14 [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"
Georg Brandlfb6fd5d2011-01-07 18:28:45 +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 Brandlfbd1b222009-12-29 21:38:35 +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 Brandlfb6fd5d2011-01-07 18:28:45 +000042 inherited by user-defined classes (for that, use :exc:`Exception`). If
Ezio Melotti985e24d2009-09-13 07:54:02 +000043 :func:`bytes` or :func:`str` is called on an instance of this class, the
Georg Brandlfb6fd5d2011-01-07 18:28:45 +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
Georg Brandl0bdfbfa2010-12-18 17:51:28 +000080.. exception:: BufferError
81
82 Raised when a :ref:`buffer <bufferobjects>` related operation cannot be
83 performed.
84
85
Georg Brandl116aa622007-08-15 14:28:22 +000086.. exception:: LookupError
87
Benjamin Petersonfa0d7032009-06-01 22:42:33 +000088 The base class for the exceptions that are raised when a key or index used on
89 a mapping or sequence is invalid: :exc:`IndexError`, :exc:`KeyError`. This
90 can be raised directly by :func:`codecs.lookup`.
Georg Brandl116aa622007-08-15 14:28:22 +000091
92
93.. exception:: EnvironmentError
94
95 The base class for exceptions that can occur outside the Python system:
96 :exc:`IOError`, :exc:`OSError`. When exceptions of this type are created with a
97 2-tuple, the first item is available on the instance's :attr:`errno` attribute
98 (it is assumed to be an error number), and the second item is available on the
99 :attr:`strerror` attribute (it is usually the associated error message). The
100 tuple itself is also available on the :attr:`args` attribute.
101
Georg Brandl116aa622007-08-15 14:28:22 +0000102 When an :exc:`EnvironmentError` exception is instantiated with a 3-tuple, the
103 first two items are available as above, while the third item is available on the
104 :attr:`filename` attribute. However, for backwards compatibility, the
105 :attr:`args` attribute contains only a 2-tuple of the first two constructor
106 arguments.
107
108 The :attr:`filename` attribute is ``None`` when this exception is created with
109 other than 3 arguments. The :attr:`errno` and :attr:`strerror` attributes are
110 also ``None`` when the instance was created with other than 2 or 3 arguments.
111 In this last case, :attr:`args` contains the verbatim constructor arguments as a
112 tuple.
113
Georg Brandl116aa622007-08-15 14:28:22 +0000114
Georg Brandlfbd1b222009-12-29 21:38:35 +0000115The following exceptions are the exceptions that are usually raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000116
117.. exception:: AssertionError
118
119 .. index:: statement: assert
120
121 Raised when an :keyword:`assert` statement fails.
122
123
124.. exception:: AttributeError
125
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000126 Raised when an attribute reference (see :ref:`attribute-references`) or
127 assignment fails. (When an object does not support attribute references or
128 attribute assignments at all, :exc:`TypeError` is raised.)
Georg Brandl116aa622007-08-15 14:28:22 +0000129
130
131.. exception:: EOFError
132
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000133 Raised when one of the built-in functions (:func:`input` or :func:`raw_input`)
134 hits an end-of-file condition (EOF) without reading any data. (N.B.: the
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000135 :meth:`file.read` and :meth:`file.readline` methods return an empty string
136 when they hit EOF.)
Georg Brandl116aa622007-08-15 14:28:22 +0000137
138
139.. exception:: FloatingPointError
140
141 Raised when a floating point operation fails. This exception is always defined,
142 but can only be raised when Python is configured with the
Éric Araujo713d3032010-11-18 16:38:46 +0000143 ``--with-fpectl`` option, or the :const:`WANT_SIGFPE_HANDLER` symbol is
Georg Brandl116aa622007-08-15 14:28:22 +0000144 defined in the :file:`pyconfig.h` file.
145
146
147.. exception:: GeneratorExit
148
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000149 Raise when a :term:`generator`\'s :meth:`close` method is called. It
150 directly inherits from :exc:`BaseException` instead of :exc:`Exception` since
151 it is technically not an error.
Georg Brandl116aa622007-08-15 14:28:22 +0000152
Georg Brandl116aa622007-08-15 14:28:22 +0000153
154.. exception:: IOError
155
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000156 Raised when an I/O operation (such as the built-in :func:`print` or
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000157 :func:`open` functions or a method of a :term:`file object`) fails for an
158 I/O-related reason, e.g., "file not found" or "disk full".
Georg Brandl116aa622007-08-15 14:28:22 +0000159
Georg Brandl116aa622007-08-15 14:28:22 +0000160 This class is derived from :exc:`EnvironmentError`. See the discussion above
161 for more information on exception instance attributes.
162
163
164.. exception:: ImportError
165
166 Raised when an :keyword:`import` statement fails to find the module definition
167 or when a ``from ... import`` fails to find a name that is to be imported.
168
Georg Brandl116aa622007-08-15 14:28:22 +0000169
170.. exception:: IndexError
171
Georg Brandl95817b32008-05-11 14:30:18 +0000172 Raised when a sequence subscript is out of range. (Slice indices are
173 silently truncated to fall in the allowed range; if an index is not an
174 integer, :exc:`TypeError` is raised.)
Georg Brandl116aa622007-08-15 14:28:22 +0000175
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000176 .. XXX xref to sequences
Georg Brandl116aa622007-08-15 14:28:22 +0000177
178
179.. exception:: KeyError
180
181 Raised when a mapping (dictionary) key is not found in the set of existing keys.
182
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000183 .. XXX xref to mapping objects?
Georg Brandl116aa622007-08-15 14:28:22 +0000184
185
186.. exception:: KeyboardInterrupt
187
188 Raised when the user hits the interrupt key (normally :kbd:`Control-C` or
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000189 :kbd:`Delete`). During execution, a check for interrupts is made
190 regularly. The exception inherits from :exc:`BaseException` so as to not be
191 accidentally caught by code that catches :exc:`Exception` and thus prevent
192 the interpreter from exiting.
Georg Brandl116aa622007-08-15 14:28:22 +0000193
Georg Brandl116aa622007-08-15 14:28:22 +0000194
195.. exception:: MemoryError
196
197 Raised when an operation runs out of memory but the situation may still be
198 rescued (by deleting some objects). The associated value is a string indicating
199 what kind of (internal) operation ran out of memory. Note that because of the
Georg Brandl60203b42010-10-06 10:11:56 +0000200 underlying memory management architecture (C's :c:func:`malloc` function), the
Georg Brandl116aa622007-08-15 14:28:22 +0000201 interpreter may not always be able to completely recover from this situation; it
202 nevertheless raises an exception so that a stack traceback can be printed, in
203 case a run-away program was the cause.
204
205
206.. exception:: NameError
207
208 Raised when a local or global name is not found. This applies only to
209 unqualified names. The associated value is an error message that includes the
210 name that could not be found.
211
212
213.. exception:: NotImplementedError
214
215 This exception is derived from :exc:`RuntimeError`. In user defined base
216 classes, abstract methods should raise this exception when they require derived
217 classes to override the method.
218
Georg Brandl116aa622007-08-15 14:28:22 +0000219
220.. exception:: OSError
221
Christian Heimesa62da1d2008-01-12 19:39:10 +0000222 .. index:: module: errno
223
224 This exception is derived from :exc:`EnvironmentError`. It is raised when a
225 function returns a system-related error (not for illegal argument types or
226 other incidental errors). The :attr:`errno` attribute is a numeric error
Georg Brandl60203b42010-10-06 10:11:56 +0000227 code from :c:data:`errno`, and the :attr:`strerror` attribute is the
228 corresponding string, as would be printed by the C function :c:func:`perror`.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000229 See the module :mod:`errno`, which contains names for the error codes defined
230 by the underlying operating system.
231
232 For exceptions that involve a file system path (such as :func:`chdir` or
233 :func:`unlink`), the exception instance will contain a third attribute,
234 :attr:`filename`, which is the file name passed to the function.
Georg Brandl116aa622007-08-15 14:28:22 +0000235
Georg Brandl116aa622007-08-15 14:28:22 +0000236
237.. exception:: OverflowError
238
239 Raised when the result of an arithmetic operation is too large to be
Georg Brandlba956ae2007-11-29 17:24:34 +0000240 represented. This cannot occur for integers (which would rather raise
Georg Brandl116aa622007-08-15 14:28:22 +0000241 :exc:`MemoryError` than give up). Because of the lack of standardization of
242 floating point exception handling in C, most floating point operations also
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000243 aren't checked.
Georg Brandl116aa622007-08-15 14:28:22 +0000244
245
246.. exception:: ReferenceError
247
248 This exception is raised when a weak reference proxy, created by the
249 :func:`weakref.proxy` function, is used to access an attribute of the referent
250 after it has been garbage collected. For more information on weak references,
251 see the :mod:`weakref` module.
252
Georg Brandl116aa622007-08-15 14:28:22 +0000253
254.. exception:: RuntimeError
255
256 Raised when an error is detected that doesn't fall in any of the other
257 categories. The associated value is a string indicating what precisely went
258 wrong. (This exception is mostly a relic from a previous version of the
259 interpreter; it is not used very much any more.)
260
261
262.. exception:: StopIteration
263
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000264 Raised by built-in function :func:`next` and an :term:`iterator`\'s
265 :meth:`__next__` method to signal that there are no further values.
Georg Brandl116aa622007-08-15 14:28:22 +0000266
Georg Brandl116aa622007-08-15 14:28:22 +0000267
268.. exception:: SyntaxError
269
270 Raised when the parser encounters a syntax error. This may occur in an
271 :keyword:`import` statement, in a call to the built-in functions :func:`exec`
272 or :func:`eval`, or when reading the initial script or standard input
273 (also interactively).
274
Georg Brandl116aa622007-08-15 14:28:22 +0000275 Instances of this class have attributes :attr:`filename`, :attr:`lineno`,
276 :attr:`offset` and :attr:`text` for easier access to the details. :func:`str`
277 of the exception instance returns only the message.
278
279
Georg Brandl0bdfbfa2010-12-18 17:51:28 +0000280.. exception:: IndentationError
281
282 Base class for syntax errors related to incorrect indentation. This is a
283 subclass of :exc:`SyntaxError`.
284
285
286.. exception:: TabError
287
288 Raised when indentation contains an inconsistent use of tabs and spaces.
289 This is a subclass of :exc:`IndentationError`.
290
291
Georg Brandl116aa622007-08-15 14:28:22 +0000292.. exception:: SystemError
293
294 Raised when the interpreter finds an internal error, but the situation does not
295 look so serious to cause it to abandon all hope. The associated value is a
296 string indicating what went wrong (in low-level terms).
297
298 You should report this to the author or maintainer of your Python interpreter.
299 Be sure to report the version of the Python interpreter (``sys.version``; it is
300 also printed at the start of an interactive Python session), the exact error
301 message (the exception's associated value) and if possible the source of the
302 program that triggered the error.
303
304
305.. exception:: SystemExit
306
307 This exception is raised by the :func:`sys.exit` function. When it is not
308 handled, the Python interpreter exits; no stack traceback is printed. If the
Georg Brandl95817b32008-05-11 14:30:18 +0000309 associated value is an integer, it specifies the system exit status (passed
Georg Brandl60203b42010-10-06 10:11:56 +0000310 to C's :c:func:`exit` function); if it is ``None``, the exit status is zero;
Georg Brandl95817b32008-05-11 14:30:18 +0000311 if it has another type (such as a string), the object's value is printed and
312 the exit status is one.
Georg Brandl116aa622007-08-15 14:28:22 +0000313
Georg Brandl116aa622007-08-15 14:28:22 +0000314 Instances have an attribute :attr:`code` which is set to the proposed exit
315 status or error message (defaulting to ``None``). Also, this exception derives
316 directly from :exc:`BaseException` and not :exc:`Exception`, since it is not
317 technically an error.
318
319 A call to :func:`sys.exit` is translated into an exception so that clean-up
320 handlers (:keyword:`finally` clauses of :keyword:`try` statements) can be
321 executed, and so that a debugger can execute a script without running the risk
322 of losing control. The :func:`os._exit` function can be used if it is
323 absolutely positively necessary to exit immediately (for example, in the child
324 process after a call to :func:`fork`).
325
326 The exception inherits from :exc:`BaseException` instead of :exc:`Exception` so
327 that it is not accidentally caught by code that catches :exc:`Exception`. This
328 allows the exception to properly propagate up and cause the interpreter to exit.
329
Georg Brandl116aa622007-08-15 14:28:22 +0000330
331.. exception:: TypeError
332
333 Raised when an operation or function is applied to an object of inappropriate
334 type. The associated value is a string giving details about the type mismatch.
335
336
337.. exception:: UnboundLocalError
338
339 Raised when a reference is made to a local variable in a function or method, but
340 no value has been bound to that variable. This is a subclass of
341 :exc:`NameError`.
342
Georg Brandl116aa622007-08-15 14:28:22 +0000343
344.. exception:: UnicodeError
345
346 Raised when a Unicode-related encoding or decoding error occurs. It is a
347 subclass of :exc:`ValueError`.
348
Georg Brandl116aa622007-08-15 14:28:22 +0000349
350.. exception:: UnicodeEncodeError
351
352 Raised when a Unicode-related error occurs during encoding. It is a subclass of
353 :exc:`UnicodeError`.
354
Georg Brandl116aa622007-08-15 14:28:22 +0000355
356.. exception:: UnicodeDecodeError
357
358 Raised when a Unicode-related error occurs during decoding. It is a subclass of
359 :exc:`UnicodeError`.
360
Georg Brandl116aa622007-08-15 14:28:22 +0000361
362.. exception:: UnicodeTranslateError
363
364 Raised when a Unicode-related error occurs during translating. It is a subclass
365 of :exc:`UnicodeError`.
366
Georg Brandl116aa622007-08-15 14:28:22 +0000367
368.. exception:: ValueError
369
370 Raised when a built-in operation or function receives an argument that has the
371 right type but an inappropriate value, and the situation is not described by a
372 more precise exception such as :exc:`IndexError`.
373
374
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000375.. exception:: VMSError
376
377 Only available on VMS. Raised when a VMS-specific error occurs.
378
379
Georg Brandl116aa622007-08-15 14:28:22 +0000380.. exception:: WindowsError
381
382 Raised when a Windows-specific error occurs or when the error number does not
Georg Brandl60203b42010-10-06 10:11:56 +0000383 correspond to an :c:data:`errno` value. The :attr:`winerror` and
Georg Brandl116aa622007-08-15 14:28:22 +0000384 :attr:`strerror` values are created from the return values of the
Georg Brandl60203b42010-10-06 10:11:56 +0000385 :c:func:`GetLastError` and :c:func:`FormatMessage` functions from the Windows
Georg Brandl116aa622007-08-15 14:28:22 +0000386 Platform API. The :attr:`errno` value maps the :attr:`winerror` value to
387 corresponding ``errno.h`` values. This is a subclass of :exc:`OSError`.
388
Georg Brandl116aa622007-08-15 14:28:22 +0000389
390.. exception:: ZeroDivisionError
391
392 Raised when the second argument of a division or modulo operation is zero. The
393 associated value is a string indicating the type of the operands and the
394 operation.
395
Georg Brandlfbd1b222009-12-29 21:38:35 +0000396
Georg Brandl116aa622007-08-15 14:28:22 +0000397The following exceptions are used as warning categories; see the :mod:`warnings`
398module for more information.
399
Georg Brandl116aa622007-08-15 14:28:22 +0000400.. exception:: Warning
401
402 Base class for warning categories.
403
404
405.. exception:: UserWarning
406
407 Base class for warnings generated by user code.
408
409
410.. exception:: DeprecationWarning
411
412 Base class for warnings about deprecated features.
413
414
415.. exception:: PendingDeprecationWarning
416
417 Base class for warnings about features which will be deprecated in the future.
418
419
420.. exception:: SyntaxWarning
421
422 Base class for warnings about dubious syntax
423
424
425.. exception:: RuntimeWarning
426
427 Base class for warnings about dubious runtime behavior.
428
429
430.. exception:: FutureWarning
431
432 Base class for warnings about constructs that will change semantically in the
433 future.
434
435
436.. exception:: ImportWarning
437
438 Base class for warnings about probable mistakes in module imports.
439
Georg Brandl116aa622007-08-15 14:28:22 +0000440
441.. exception:: UnicodeWarning
442
443 Base class for warnings related to Unicode.
444
Georg Brandl08be72d2010-10-24 15:11:22 +0000445
Guido van Rossum98297ee2007-11-06 21:34:58 +0000446.. exception:: BytesWarning
Georg Brandl116aa622007-08-15 14:28:22 +0000447
Guido van Rossum98297ee2007-11-06 21:34:58 +0000448 Base class for warnings related to :class:`bytes` and :class:`buffer`.
449
Georg Brandl08be72d2010-10-24 15:11:22 +0000450
451.. exception:: ResourceWarning
452
453 Base class for warnings related to resource usage.
454
455 .. versionadded:: 3.2
456
457
458
Alexandre Vassalottic22c6f22009-07-21 00:51:58 +0000459Exception hierarchy
460-------------------
Guido van Rossum98297ee2007-11-06 21:34:58 +0000461
462The class hierarchy for built-in exceptions is:
Georg Brandl116aa622007-08-15 14:28:22 +0000463
464.. literalinclude:: ../../Lib/test/exception_hierarchy.txt