blob: 70591d15f2fc3062d6d8b77c12149b5405773d92 [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
66.. exception:: LookupError
67
Benjamin Petersonfa0d7032009-06-01 22:42:33 +000068 The base class for the exceptions that are raised when a key or index used on
69 a mapping or sequence is invalid: :exc:`IndexError`, :exc:`KeyError`. This
70 can be raised directly by :func:`codecs.lookup`.
Georg Brandl116aa622007-08-15 14:28:22 +000071
72
73.. exception:: EnvironmentError
74
75 The base class for exceptions that can occur outside the Python system:
76 :exc:`IOError`, :exc:`OSError`. When exceptions of this type are created with a
77 2-tuple, the first item is available on the instance's :attr:`errno` attribute
78 (it is assumed to be an error number), and the second item is available on the
79 :attr:`strerror` attribute (it is usually the associated error message). The
80 tuple itself is also available on the :attr:`args` attribute.
81
Georg Brandl116aa622007-08-15 14:28:22 +000082 When an :exc:`EnvironmentError` exception is instantiated with a 3-tuple, the
83 first two items are available as above, while the third item is available on the
84 :attr:`filename` attribute. However, for backwards compatibility, the
85 :attr:`args` attribute contains only a 2-tuple of the first two constructor
86 arguments.
87
88 The :attr:`filename` attribute is ``None`` when this exception is created with
89 other than 3 arguments. The :attr:`errno` and :attr:`strerror` attributes are
90 also ``None`` when the instance was created with other than 2 or 3 arguments.
91 In this last case, :attr:`args` contains the verbatim constructor arguments as a
92 tuple.
93
Georg Brandl116aa622007-08-15 14:28:22 +000094
Georg Brandlfbd1b222009-12-29 21:38:35 +000095The following exceptions are the exceptions that are usually raised.
Georg Brandl116aa622007-08-15 14:28:22 +000096
97.. exception:: AssertionError
98
99 .. index:: statement: assert
100
101 Raised when an :keyword:`assert` statement fails.
102
103
104.. exception:: AttributeError
105
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000106 Raised when an attribute reference (see :ref:`attribute-references`) or
107 assignment fails. (When an object does not support attribute references or
108 attribute assignments at all, :exc:`TypeError` is raised.)
Georg Brandl116aa622007-08-15 14:28:22 +0000109
110
111.. exception:: EOFError
112
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000113 Raised when one of the built-in functions (:func:`input` or :func:`raw_input`)
114 hits an end-of-file condition (EOF) without reading any data. (N.B.: the
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000115 :meth:`file.read` and :meth:`file.readline` methods return an empty string
116 when they hit EOF.)
Georg Brandl116aa622007-08-15 14:28:22 +0000117
118
119.. exception:: FloatingPointError
120
121 Raised when a floating point operation fails. This exception is always defined,
122 but can only be raised when Python is configured with the
Éric Araujo713d3032010-11-18 16:38:46 +0000123 ``--with-fpectl`` option, or the :const:`WANT_SIGFPE_HANDLER` symbol is
Georg Brandl116aa622007-08-15 14:28:22 +0000124 defined in the :file:`pyconfig.h` file.
125
126
127.. exception:: GeneratorExit
128
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000129 Raise when a :term:`generator`\'s :meth:`close` method is called. It
130 directly inherits from :exc:`BaseException` instead of :exc:`Exception` since
131 it is technically not an error.
Georg Brandl116aa622007-08-15 14:28:22 +0000132
Georg Brandl116aa622007-08-15 14:28:22 +0000133
134.. exception:: IOError
135
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000136 Raised when an I/O operation (such as the built-in :func:`print` or
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000137 :func:`open` functions or a method of a :term:`file object`) fails for an
138 I/O-related reason, e.g., "file not found" or "disk full".
Georg Brandl116aa622007-08-15 14:28:22 +0000139
Georg Brandl116aa622007-08-15 14:28:22 +0000140 This class is derived from :exc:`EnvironmentError`. See the discussion above
141 for more information on exception instance attributes.
142
143
144.. exception:: ImportError
145
146 Raised when an :keyword:`import` statement fails to find the module definition
147 or when a ``from ... import`` fails to find a name that is to be imported.
148
Georg Brandl116aa622007-08-15 14:28:22 +0000149
150.. exception:: IndexError
151
Georg Brandl95817b32008-05-11 14:30:18 +0000152 Raised when a sequence subscript is out of range. (Slice indices are
153 silently truncated to fall in the allowed range; if an index is not an
154 integer, :exc:`TypeError` is raised.)
Georg Brandl116aa622007-08-15 14:28:22 +0000155
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000156 .. XXX xref to sequences
Georg Brandl116aa622007-08-15 14:28:22 +0000157
158
159.. exception:: KeyError
160
161 Raised when a mapping (dictionary) key is not found in the set of existing keys.
162
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000163 .. XXX xref to mapping objects?
Georg Brandl116aa622007-08-15 14:28:22 +0000164
165
166.. exception:: KeyboardInterrupt
167
168 Raised when the user hits the interrupt key (normally :kbd:`Control-C` or
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000169 :kbd:`Delete`). During execution, a check for interrupts is made
170 regularly. The exception inherits from :exc:`BaseException` so as to not be
171 accidentally caught by code that catches :exc:`Exception` and thus prevent
172 the interpreter from exiting.
Georg Brandl116aa622007-08-15 14:28:22 +0000173
Georg Brandl116aa622007-08-15 14:28:22 +0000174
175.. exception:: MemoryError
176
177 Raised when an operation runs out of memory but the situation may still be
178 rescued (by deleting some objects). The associated value is a string indicating
179 what kind of (internal) operation ran out of memory. Note that because of the
Georg Brandl60203b42010-10-06 10:11:56 +0000180 underlying memory management architecture (C's :c:func:`malloc` function), the
Georg Brandl116aa622007-08-15 14:28:22 +0000181 interpreter may not always be able to completely recover from this situation; it
182 nevertheless raises an exception so that a stack traceback can be printed, in
183 case a run-away program was the cause.
184
185
186.. exception:: NameError
187
188 Raised when a local or global name is not found. This applies only to
189 unqualified names. The associated value is an error message that includes the
190 name that could not be found.
191
192
193.. exception:: NotImplementedError
194
195 This exception is derived from :exc:`RuntimeError`. In user defined base
196 classes, abstract methods should raise this exception when they require derived
197 classes to override the method.
198
Georg Brandl116aa622007-08-15 14:28:22 +0000199
200.. exception:: OSError
201
Christian Heimesa62da1d2008-01-12 19:39:10 +0000202 .. index:: module: errno
203
204 This exception is derived from :exc:`EnvironmentError`. It is raised when a
205 function returns a system-related error (not for illegal argument types or
206 other incidental errors). The :attr:`errno` attribute is a numeric error
Georg Brandl60203b42010-10-06 10:11:56 +0000207 code from :c:data:`errno`, and the :attr:`strerror` attribute is the
208 corresponding string, as would be printed by the C function :c:func:`perror`.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000209 See the module :mod:`errno`, which contains names for the error codes defined
210 by the underlying operating system.
211
212 For exceptions that involve a file system path (such as :func:`chdir` or
213 :func:`unlink`), the exception instance will contain a third attribute,
214 :attr:`filename`, which is the file name passed to the function.
Georg Brandl116aa622007-08-15 14:28:22 +0000215
Georg Brandl116aa622007-08-15 14:28:22 +0000216
217.. exception:: OverflowError
218
219 Raised when the result of an arithmetic operation is too large to be
Georg Brandlba956ae2007-11-29 17:24:34 +0000220 represented. This cannot occur for integers (which would rather raise
Georg Brandl116aa622007-08-15 14:28:22 +0000221 :exc:`MemoryError` than give up). Because of the lack of standardization of
222 floating point exception handling in C, most floating point operations also
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000223 aren't checked.
Georg Brandl116aa622007-08-15 14:28:22 +0000224
225
226.. exception:: ReferenceError
227
228 This exception is raised when a weak reference proxy, created by the
229 :func:`weakref.proxy` function, is used to access an attribute of the referent
230 after it has been garbage collected. For more information on weak references,
231 see the :mod:`weakref` module.
232
Georg Brandl116aa622007-08-15 14:28:22 +0000233
234.. exception:: RuntimeError
235
236 Raised when an error is detected that doesn't fall in any of the other
237 categories. The associated value is a string indicating what precisely went
238 wrong. (This exception is mostly a relic from a previous version of the
239 interpreter; it is not used very much any more.)
240
241
242.. exception:: StopIteration
243
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000244 Raised by built-in function :func:`next` and an :term:`iterator`\'s
245 :meth:`__next__` method to signal that there are no further values.
Georg Brandl116aa622007-08-15 14:28:22 +0000246
Georg Brandl116aa622007-08-15 14:28:22 +0000247
248.. exception:: SyntaxError
249
250 Raised when the parser encounters a syntax error. This may occur in an
251 :keyword:`import` statement, in a call to the built-in functions :func:`exec`
252 or :func:`eval`, or when reading the initial script or standard input
253 (also interactively).
254
Georg Brandl116aa622007-08-15 14:28:22 +0000255 Instances of this class have attributes :attr:`filename`, :attr:`lineno`,
256 :attr:`offset` and :attr:`text` for easier access to the details. :func:`str`
257 of the exception instance returns only the message.
258
259
260.. exception:: SystemError
261
262 Raised when the interpreter finds an internal error, but the situation does not
263 look so serious to cause it to abandon all hope. The associated value is a
264 string indicating what went wrong (in low-level terms).
265
266 You should report this to the author or maintainer of your Python interpreter.
267 Be sure to report the version of the Python interpreter (``sys.version``; it is
268 also printed at the start of an interactive Python session), the exact error
269 message (the exception's associated value) and if possible the source of the
270 program that triggered the error.
271
272
273.. exception:: SystemExit
274
275 This exception is raised by the :func:`sys.exit` function. When it is not
276 handled, the Python interpreter exits; no stack traceback is printed. If the
Georg Brandl95817b32008-05-11 14:30:18 +0000277 associated value is an integer, it specifies the system exit status (passed
Georg Brandl60203b42010-10-06 10:11:56 +0000278 to C's :c:func:`exit` function); if it is ``None``, the exit status is zero;
Georg Brandl95817b32008-05-11 14:30:18 +0000279 if it has another type (such as a string), the object's value is printed and
280 the exit status is one.
Georg Brandl116aa622007-08-15 14:28:22 +0000281
Georg Brandl116aa622007-08-15 14:28:22 +0000282 Instances have an attribute :attr:`code` which is set to the proposed exit
283 status or error message (defaulting to ``None``). Also, this exception derives
284 directly from :exc:`BaseException` and not :exc:`Exception`, since it is not
285 technically an error.
286
287 A call to :func:`sys.exit` is translated into an exception so that clean-up
288 handlers (:keyword:`finally` clauses of :keyword:`try` statements) can be
289 executed, and so that a debugger can execute a script without running the risk
290 of losing control. The :func:`os._exit` function can be used if it is
291 absolutely positively necessary to exit immediately (for example, in the child
292 process after a call to :func:`fork`).
293
294 The exception inherits from :exc:`BaseException` instead of :exc:`Exception` so
295 that it is not accidentally caught by code that catches :exc:`Exception`. This
296 allows the exception to properly propagate up and cause the interpreter to exit.
297
Georg Brandl116aa622007-08-15 14:28:22 +0000298
299.. exception:: TypeError
300
301 Raised when an operation or function is applied to an object of inappropriate
302 type. The associated value is a string giving details about the type mismatch.
303
304
305.. exception:: UnboundLocalError
306
307 Raised when a reference is made to a local variable in a function or method, but
308 no value has been bound to that variable. This is a subclass of
309 :exc:`NameError`.
310
Georg Brandl116aa622007-08-15 14:28:22 +0000311
312.. exception:: UnicodeError
313
314 Raised when a Unicode-related encoding or decoding error occurs. It is a
315 subclass of :exc:`ValueError`.
316
Georg Brandl116aa622007-08-15 14:28:22 +0000317
318.. exception:: UnicodeEncodeError
319
320 Raised when a Unicode-related error occurs during encoding. It is a subclass of
321 :exc:`UnicodeError`.
322
Georg Brandl116aa622007-08-15 14:28:22 +0000323
324.. exception:: UnicodeDecodeError
325
326 Raised when a Unicode-related error occurs during decoding. It is a subclass of
327 :exc:`UnicodeError`.
328
Georg Brandl116aa622007-08-15 14:28:22 +0000329
330.. exception:: UnicodeTranslateError
331
332 Raised when a Unicode-related error occurs during translating. It is a subclass
333 of :exc:`UnicodeError`.
334
Georg Brandl116aa622007-08-15 14:28:22 +0000335
336.. exception:: ValueError
337
338 Raised when a built-in operation or function receives an argument that has the
339 right type but an inappropriate value, and the situation is not described by a
340 more precise exception such as :exc:`IndexError`.
341
342
Benjamin Petersond75fcb42009-02-19 04:22:03 +0000343.. exception:: VMSError
344
345 Only available on VMS. Raised when a VMS-specific error occurs.
346
347
Georg Brandl116aa622007-08-15 14:28:22 +0000348.. exception:: WindowsError
349
350 Raised when a Windows-specific error occurs or when the error number does not
Georg Brandl60203b42010-10-06 10:11:56 +0000351 correspond to an :c:data:`errno` value. The :attr:`winerror` and
Georg Brandl116aa622007-08-15 14:28:22 +0000352 :attr:`strerror` values are created from the return values of the
Georg Brandl60203b42010-10-06 10:11:56 +0000353 :c:func:`GetLastError` and :c:func:`FormatMessage` functions from the Windows
Georg Brandl116aa622007-08-15 14:28:22 +0000354 Platform API. The :attr:`errno` value maps the :attr:`winerror` value to
355 corresponding ``errno.h`` values. This is a subclass of :exc:`OSError`.
356
Georg Brandl116aa622007-08-15 14:28:22 +0000357
358.. exception:: ZeroDivisionError
359
360 Raised when the second argument of a division or modulo operation is zero. The
361 associated value is a string indicating the type of the operands and the
362 operation.
363
Georg Brandlfbd1b222009-12-29 21:38:35 +0000364
Georg Brandl116aa622007-08-15 14:28:22 +0000365The following exceptions are used as warning categories; see the :mod:`warnings`
366module for more information.
367
Georg Brandl116aa622007-08-15 14:28:22 +0000368.. exception:: Warning
369
370 Base class for warning categories.
371
372
373.. exception:: UserWarning
374
375 Base class for warnings generated by user code.
376
377
378.. exception:: DeprecationWarning
379
380 Base class for warnings about deprecated features.
381
382
383.. exception:: PendingDeprecationWarning
384
385 Base class for warnings about features which will be deprecated in the future.
386
387
388.. exception:: SyntaxWarning
389
390 Base class for warnings about dubious syntax
391
392
393.. exception:: RuntimeWarning
394
395 Base class for warnings about dubious runtime behavior.
396
397
398.. exception:: FutureWarning
399
400 Base class for warnings about constructs that will change semantically in the
401 future.
402
403
404.. exception:: ImportWarning
405
406 Base class for warnings about probable mistakes in module imports.
407
Georg Brandl116aa622007-08-15 14:28:22 +0000408
409.. exception:: UnicodeWarning
410
411 Base class for warnings related to Unicode.
412
Georg Brandl08be72d2010-10-24 15:11:22 +0000413
Guido van Rossum98297ee2007-11-06 21:34:58 +0000414.. exception:: BytesWarning
Georg Brandl116aa622007-08-15 14:28:22 +0000415
Guido van Rossum98297ee2007-11-06 21:34:58 +0000416 Base class for warnings related to :class:`bytes` and :class:`buffer`.
417
Georg Brandl08be72d2010-10-24 15:11:22 +0000418
419.. exception:: ResourceWarning
420
421 Base class for warnings related to resource usage.
422
423 .. versionadded:: 3.2
424
425
426
Alexandre Vassalottic22c6f22009-07-21 00:51:58 +0000427Exception hierarchy
428-------------------
Guido van Rossum98297ee2007-11-06 21:34:58 +0000429
430The class hierarchy for built-in exceptions is:
Georg Brandl116aa622007-08-15 14:28:22 +0000431
432.. literalinclude:: ../../Lib/test/exception_hierarchy.txt