blob: f9a6bee64d0862e180a51364e9f77749a5f36ede [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001.. _bltin-exceptions:
2
3Built-in Exceptions
4===================
5
6.. module:: exceptions
7 :synopsis: Standard exception classes.
8
9
10Exceptions should be class objects. The exceptions are defined in the module
11:mod:`exceptions`. This module never needs to be imported explicitly: the
12exceptions are provided in the built-in namespace as well as the
13:mod:`exceptions` module.
14
15.. index::
16 statement: try
17 statement: except
18
19For class exceptions, in a :keyword:`try` statement with an :keyword:`except`
20clause that mentions a particular class, that clause also handles any exception
21classes derived from that class (but not exception classes from which *it* is
22derived). Two exception classes that are not related via subclassing are never
23equivalent, even if they have the same name.
24
25.. index:: statement: raise
26
27The built-in exceptions listed below can be generated by the interpreter or
28built-in functions. Except where mentioned, they have an "associated value"
Georg Brandl335d4f52011-01-09 07:58:45 +000029indicating the detailed cause of the error. This may be a string or a tuple
Georg Brandl8ec7f652007-08-15 14:28:01 +000030containing several items of information (e.g., an error code and a string
31explaining the code). The associated value is the second argument to the
32:keyword:`raise` statement. If the exception class is derived from the standard
33root class :exc:`BaseException`, the associated value is present as the
34exception instance's :attr:`args` attribute.
35
36User code can raise built-in exceptions. This can be used to test an exception
37handler or to report an error condition "just like" the situation in which the
38interpreter raises the same exception; but beware that there is nothing to
39prevent user code from raising an inappropriate error.
40
41The built-in exception classes can be sub-classed to define new exceptions;
42programmers are encouraged to at least derive new exceptions from the
43:exc:`Exception` class and not :exc:`BaseException`. More information on
44defining exceptions is available in the Python Tutorial under
45:ref:`tut-userexceptions`.
46
47The following exceptions are only used as base classes for other exceptions.
48
Georg Brandl8ec7f652007-08-15 14:28:01 +000049.. exception:: BaseException
50
51 The base class for all built-in exceptions. It is not meant to be directly
Georg Brandl335d4f52011-01-09 07:58:45 +000052 inherited by user-defined classes (for that, use :exc:`Exception`). If
Georg Brandl8ec7f652007-08-15 14:28:01 +000053 :func:`str` or :func:`unicode` is called on an instance of this class, the
Georg Brandl335d4f52011-01-09 07:58:45 +000054 representation of the argument(s) to the instance are returned, or the empty
55 string when there were no arguments.
Georg Brandl8ec7f652007-08-15 14:28:01 +000056
57 .. versionadded:: 2.5
58
Georg Brandl335d4f52011-01-09 07:58:45 +000059 .. attribute:: args
60
61 The tuple of arguments given to the exception constructor. Some built-in
62 exceptions (like :exc:`IOError`) expect a certain number of arguments and
63 assign a special meaning to the elements of this tuple, while others are
64 usually called only with a single string giving an error message.
65
66 .. method:: with_traceback(tb)
67
68 This method sets *tb* as the new traceback for the exception and returns
69 the exception object. It is usually used in exception handling code like
70 this::
71
72 try:
73 ...
74 except SomeException:
75 tb = sys.exc_info()[2]
76 raise OtherException(...).with_traceback(tb)
77
Georg Brandl8ec7f652007-08-15 14:28:01 +000078
79.. exception:: Exception
80
81 All built-in, non-system-exiting exceptions are derived from this class. All
82 user-defined exceptions should also be derived from this class.
83
84 .. versionchanged:: 2.5
85 Changed to inherit from :exc:`BaseException`.
86
87
88.. exception:: StandardError
89
90 The base class for all built-in exceptions except :exc:`StopIteration`,
91 :exc:`GeneratorExit`, :exc:`KeyboardInterrupt` and :exc:`SystemExit`.
92 :exc:`StandardError` itself is derived from :exc:`Exception`.
93
94
95.. exception:: ArithmeticError
96
97 The base class for those built-in exceptions that are raised for various
98 arithmetic errors: :exc:`OverflowError`, :exc:`ZeroDivisionError`,
99 :exc:`FloatingPointError`.
100
101
102.. exception:: LookupError
103
Benjamin Peterson3dabc102009-05-10 23:52:09 +0000104 The base class for the exceptions that are raised when a key or index used on
105 a mapping or sequence is invalid: :exc:`IndexError`, :exc:`KeyError`. This
106 can be raised directly by :func:`codecs.lookup`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000107
108
109.. exception:: EnvironmentError
110
111 The base class for exceptions that can occur outside the Python system:
112 :exc:`IOError`, :exc:`OSError`. When exceptions of this type are created with a
113 2-tuple, the first item is available on the instance's :attr:`errno` attribute
114 (it is assumed to be an error number), and the second item is available on the
115 :attr:`strerror` attribute (it is usually the associated error message). The
116 tuple itself is also available on the :attr:`args` attribute.
117
118 .. versionadded:: 1.5.2
119
120 When an :exc:`EnvironmentError` exception is instantiated with a 3-tuple, the
121 first two items are available as above, while the third item is available on the
122 :attr:`filename` attribute. However, for backwards compatibility, the
123 :attr:`args` attribute contains only a 2-tuple of the first two constructor
124 arguments.
125
126 The :attr:`filename` attribute is ``None`` when this exception is created with
127 other than 3 arguments. The :attr:`errno` and :attr:`strerror` attributes are
128 also ``None`` when the instance was created with other than 2 or 3 arguments.
129 In this last case, :attr:`args` contains the verbatim constructor arguments as a
130 tuple.
131
132The following exceptions are the exceptions that are actually raised.
133
134
135.. exception:: AssertionError
136
137 .. index:: statement: assert
138
139 Raised when an :keyword:`assert` statement fails.
140
141
142.. exception:: AttributeError
143
Georg Brandlb19be572007-12-29 10:57:00 +0000144 Raised when an attribute reference (see :ref:`attribute-references`) or
145 assignment fails. (When an object does not support attribute references or
146 attribute assignments at all, :exc:`TypeError` is raised.)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000147
148
149.. exception:: EOFError
150
151 Raised when one of the built-in functions (:func:`input` or :func:`raw_input`)
152 hits an end-of-file condition (EOF) without reading any data. (N.B.: the
Georg Brandlb19be572007-12-29 10:57:00 +0000153 :meth:`file.read` and :meth:`file.readline` methods return an empty string
Georg Brandl8ec7f652007-08-15 14:28:01 +0000154 when they hit EOF.)
155
Georg Brandl8ec7f652007-08-15 14:28:01 +0000156
157.. exception:: FloatingPointError
158
159 Raised when a floating point operation fails. This exception is always defined,
160 but can only be raised when Python is configured with the
Éric Araujoa8132ec2010-12-16 03:53:53 +0000161 ``--with-fpectl`` option, or the :const:`WANT_SIGFPE_HANDLER` symbol is
Georg Brandl8ec7f652007-08-15 14:28:01 +0000162 defined in the :file:`pyconfig.h` file.
163
164
165.. exception:: GeneratorExit
166
Georg Brandlcf3fb252007-10-21 10:52:38 +0000167 Raise when a :term:`generator`\'s :meth:`close` method is called. It
Christian Heimes44eeaec2007-12-03 20:01:02 +0000168 directly inherits from :exc:`BaseException` instead of :exc:`StandardError` since
Georg Brandlcf3fb252007-10-21 10:52:38 +0000169 it is technically not an error.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000170
171 .. versionadded:: 2.5
172
Christian Heimes44eeaec2007-12-03 20:01:02 +0000173 .. versionchanged:: 2.6
174 Changed to inherit from :exc:`BaseException`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000175
176.. exception:: IOError
177
178 Raised when an I/O operation (such as a :keyword:`print` statement, the built-in
179 :func:`open` function or a method of a file object) fails for an I/O-related
180 reason, e.g., "file not found" or "disk full".
181
Georg Brandl8ec7f652007-08-15 14:28:01 +0000182 This class is derived from :exc:`EnvironmentError`. See the discussion above
183 for more information on exception instance attributes.
184
Gregory P. Smithe9fef692007-09-09 23:36:46 +0000185 .. versionchanged:: 2.6
186 Changed :exc:`socket.error` to use this as a base class.
187
Georg Brandl8ec7f652007-08-15 14:28:01 +0000188
189.. exception:: ImportError
190
191 Raised when an :keyword:`import` statement fails to find the module definition
192 or when a ``from ... import`` fails to find a name that is to be imported.
193
Georg Brandl8ec7f652007-08-15 14:28:01 +0000194
195.. exception:: IndexError
196
197 Raised when a sequence subscript is out of range. (Slice indices are silently
198 truncated to fall in the allowed range; if an index is not a plain integer,
199 :exc:`TypeError` is raised.)
200
Georg Brandlb19be572007-12-29 10:57:00 +0000201 .. XXX xref to sequences
Georg Brandl8ec7f652007-08-15 14:28:01 +0000202
203
204.. exception:: KeyError
205
206 Raised when a mapping (dictionary) key is not found in the set of existing keys.
207
Georg Brandlb19be572007-12-29 10:57:00 +0000208 .. XXX xref to mapping objects?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000209
210
211.. exception:: KeyboardInterrupt
212
213 Raised when the user hits the interrupt key (normally :kbd:`Control-C` or
214 :kbd:`Delete`). During execution, a check for interrupts is made regularly.
215 Interrupts typed when a built-in function :func:`input` or :func:`raw_input` is
216 waiting for input also raise this exception. The exception inherits from
217 :exc:`BaseException` so as to not be accidentally caught by code that catches
218 :exc:`Exception` and thus prevent the interpreter from exiting.
219
Georg Brandl8ec7f652007-08-15 14:28:01 +0000220 .. versionchanged:: 2.5
221 Changed to inherit from :exc:`BaseException`.
222
223
224.. exception:: MemoryError
225
226 Raised when an operation runs out of memory but the situation may still be
227 rescued (by deleting some objects). The associated value is a string indicating
228 what kind of (internal) operation ran out of memory. Note that because of the
229 underlying memory management architecture (C's :cfunc:`malloc` function), the
230 interpreter may not always be able to completely recover from this situation; it
231 nevertheless raises an exception so that a stack traceback can be printed, in
232 case a run-away program was the cause.
233
234
235.. exception:: NameError
236
237 Raised when a local or global name is not found. This applies only to
238 unqualified names. The associated value is an error message that includes the
239 name that could not be found.
240
241
242.. exception:: NotImplementedError
243
244 This exception is derived from :exc:`RuntimeError`. In user defined base
245 classes, abstract methods should raise this exception when they require derived
246 classes to override the method.
247
248 .. versionadded:: 1.5.2
249
250
251.. exception:: OSError
252
Georg Brandl57fe0f22008-01-12 10:53:29 +0000253 .. index:: module: errno
254
255 This exception is derived from :exc:`EnvironmentError`. It is raised when a
256 function returns a system-related error (not for illegal argument types or
257 other incidental errors). The :attr:`errno` attribute is a numeric error
258 code from :cdata:`errno`, and the :attr:`strerror` attribute is the
259 corresponding string, as would be printed by the C function :cfunc:`perror`.
260 See the module :mod:`errno`, which contains names for the error codes defined
261 by the underlying operating system.
262
263 For exceptions that involve a file system path (such as :func:`chdir` or
264 :func:`unlink`), the exception instance will contain a third attribute,
265 :attr:`filename`, which is the file name passed to the function.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000266
Georg Brandlfca4e1f2008-01-12 16:11:09 +0000267 .. versionadded:: 1.5.2
268
Georg Brandl8ec7f652007-08-15 14:28:01 +0000269
270.. exception:: OverflowError
271
272 Raised when the result of an arithmetic operation is too large to be
273 represented. This cannot occur for long integers (which would rather raise
Georg Brandle9135ba2008-05-11 10:55:59 +0000274 :exc:`MemoryError` than give up) and for most operations with plain integers,
275 which return a long integer instead. Because of the lack of standardization
276 of floating point exception handling in C, most floating point operations
277 also aren't checked.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000278
Georg Brandl8ec7f652007-08-15 14:28:01 +0000279
280.. exception:: ReferenceError
281
282 This exception is raised when a weak reference proxy, created by the
283 :func:`weakref.proxy` function, is used to access an attribute of the referent
284 after it has been garbage collected. For more information on weak references,
285 see the :mod:`weakref` module.
286
287 .. versionadded:: 2.2
288 Previously known as the :exc:`weakref.ReferenceError` exception.
289
290
291.. exception:: RuntimeError
292
293 Raised when an error is detected that doesn't fall in any of the other
294 categories. The associated value is a string indicating what precisely went
295 wrong. (This exception is mostly a relic from a previous version of the
296 interpreter; it is not used very much any more.)
297
298
299.. exception:: StopIteration
300
Georg Brandl9fa61bb2009-07-26 14:19:57 +0000301 Raised by an :term:`iterator`\'s :meth:`~iterator.next` method to signal that
302 there are no further values. This is derived from :exc:`Exception` rather
303 than :exc:`StandardError`, since this is not considered an error in its
304 normal application.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000305
306 .. versionadded:: 2.2
307
308
309.. exception:: SyntaxError
310
311 Raised when the parser encounters a syntax error. This may occur in an
312 :keyword:`import` statement, in an :keyword:`exec` statement, in a call to the
313 built-in function :func:`eval` or :func:`input`, or when reading the initial
314 script or standard input (also interactively).
315
Georg Brandl8ec7f652007-08-15 14:28:01 +0000316 Instances of this class have attributes :attr:`filename`, :attr:`lineno`,
317 :attr:`offset` and :attr:`text` for easier access to the details. :func:`str`
318 of the exception instance returns only the message.
319
320
321.. exception:: SystemError
322
323 Raised when the interpreter finds an internal error, but the situation does not
324 look so serious to cause it to abandon all hope. The associated value is a
325 string indicating what went wrong (in low-level terms).
326
327 You should report this to the author or maintainer of your Python interpreter.
328 Be sure to report the version of the Python interpreter (``sys.version``; it is
329 also printed at the start of an interactive Python session), the exact error
330 message (the exception's associated value) and if possible the source of the
331 program that triggered the error.
332
333
334.. exception:: SystemExit
335
336 This exception is raised by the :func:`sys.exit` function. When it is not
337 handled, the Python interpreter exits; no stack traceback is printed. If the
338 associated value is a plain integer, it specifies the system exit status (passed
339 to C's :cfunc:`exit` function); if it is ``None``, the exit status is zero; if
340 it has another type (such as a string), the object's value is printed and the
341 exit status is one.
342
Georg Brandl8ec7f652007-08-15 14:28:01 +0000343 Instances have an attribute :attr:`code` which is set to the proposed exit
344 status or error message (defaulting to ``None``). Also, this exception derives
345 directly from :exc:`BaseException` and not :exc:`StandardError`, since it is not
346 technically an error.
347
348 A call to :func:`sys.exit` is translated into an exception so that clean-up
349 handlers (:keyword:`finally` clauses of :keyword:`try` statements) can be
350 executed, and so that a debugger can execute a script without running the risk
351 of losing control. The :func:`os._exit` function can be used if it is
352 absolutely positively necessary to exit immediately (for example, in the child
353 process after a call to :func:`fork`).
354
355 The exception inherits from :exc:`BaseException` instead of :exc:`StandardError`
356 or :exc:`Exception` so that it is not accidentally caught by code that catches
357 :exc:`Exception`. This allows the exception to properly propagate up and cause
358 the interpreter to exit.
359
360 .. versionchanged:: 2.5
361 Changed to inherit from :exc:`BaseException`.
362
363
364.. exception:: TypeError
365
366 Raised when an operation or function is applied to an object of inappropriate
367 type. The associated value is a string giving details about the type mismatch.
368
369
370.. exception:: UnboundLocalError
371
372 Raised when a reference is made to a local variable in a function or method, but
373 no value has been bound to that variable. This is a subclass of
374 :exc:`NameError`.
375
376 .. versionadded:: 2.0
377
378
379.. exception:: UnicodeError
380
381 Raised when a Unicode-related encoding or decoding error occurs. It is a
382 subclass of :exc:`ValueError`.
383
384 .. versionadded:: 2.0
385
386
387.. exception:: UnicodeEncodeError
388
389 Raised when a Unicode-related error occurs during encoding. It is a subclass of
390 :exc:`UnicodeError`.
391
392 .. versionadded:: 2.3
393
394
395.. exception:: UnicodeDecodeError
396
397 Raised when a Unicode-related error occurs during decoding. It is a subclass of
398 :exc:`UnicodeError`.
399
400 .. versionadded:: 2.3
401
402
403.. exception:: UnicodeTranslateError
404
405 Raised when a Unicode-related error occurs during translating. It is a subclass
406 of :exc:`UnicodeError`.
407
408 .. versionadded:: 2.3
409
410
411.. exception:: ValueError
412
413 Raised when a built-in operation or function receives an argument that has the
414 right type but an inappropriate value, and the situation is not described by a
415 more precise exception such as :exc:`IndexError`.
416
417
Georg Brandl580d7c12009-02-18 00:31:36 +0000418.. exception:: VMSError
419
420 Only available on VMS. Raised when a VMS-specific error occurs.
421
422
Georg Brandl8ec7f652007-08-15 14:28:01 +0000423.. exception:: WindowsError
424
425 Raised when a Windows-specific error occurs or when the error number does not
426 correspond to an :cdata:`errno` value. The :attr:`winerror` and
427 :attr:`strerror` values are created from the return values of the
428 :cfunc:`GetLastError` and :cfunc:`FormatMessage` functions from the Windows
429 Platform API. The :attr:`errno` value maps the :attr:`winerror` value to
430 corresponding ``errno.h`` values. This is a subclass of :exc:`OSError`.
431
432 .. versionadded:: 2.0
433
434 .. versionchanged:: 2.5
435 Previous versions put the :cfunc:`GetLastError` codes into :attr:`errno`.
436
437
438.. exception:: ZeroDivisionError
439
440 Raised when the second argument of a division or modulo operation is zero. The
441 associated value is a string indicating the type of the operands and the
442 operation.
443
444The following exceptions are used as warning categories; see the :mod:`warnings`
445module for more information.
446
447
448.. exception:: Warning
449
450 Base class for warning categories.
451
452
453.. exception:: UserWarning
454
455 Base class for warnings generated by user code.
456
457
458.. exception:: DeprecationWarning
459
460 Base class for warnings about deprecated features.
461
462
463.. exception:: PendingDeprecationWarning
464
465 Base class for warnings about features which will be deprecated in the future.
466
467
468.. exception:: SyntaxWarning
469
470 Base class for warnings about dubious syntax
471
472
473.. exception:: RuntimeWarning
474
475 Base class for warnings about dubious runtime behavior.
476
477
478.. exception:: FutureWarning
479
480 Base class for warnings about constructs that will change semantically in the
481 future.
482
483
484.. exception:: ImportWarning
485
486 Base class for warnings about probable mistakes in module imports.
487
488 .. versionadded:: 2.5
489
490
491.. exception:: UnicodeWarning
492
493 Base class for warnings related to Unicode.
494
495 .. versionadded:: 2.5
496
Georg Brandl8ec7f652007-08-15 14:28:01 +0000497
Georg Brandl3cd0bed2009-06-30 16:18:55 +0000498Exception hierarchy
499-------------------
500
501The class hierarchy for built-in exceptions is:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000502
503.. literalinclude:: ../../Lib/test/exception_hierarchy.txt