blob: 58867685675b2341a436191173bf08e3650ab765 [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
Georg Brandl28dadd92011-02-25 10:50:32 +0000102.. exception:: BufferError
103
104 Raised when a :ref:`buffer <bufferobjects>` related operation cannot be
105 performed.
106
107
Georg Brandl8ec7f652007-08-15 14:28:01 +0000108.. exception:: LookupError
109
Benjamin Peterson3dabc102009-05-10 23:52:09 +0000110 The base class for the exceptions that are raised when a key or index used on
111 a mapping or sequence is invalid: :exc:`IndexError`, :exc:`KeyError`. This
112 can be raised directly by :func:`codecs.lookup`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000113
114
115.. exception:: EnvironmentError
116
117 The base class for exceptions that can occur outside the Python system:
118 :exc:`IOError`, :exc:`OSError`. When exceptions of this type are created with a
119 2-tuple, the first item is available on the instance's :attr:`errno` attribute
120 (it is assumed to be an error number), and the second item is available on the
121 :attr:`strerror` attribute (it is usually the associated error message). The
122 tuple itself is also available on the :attr:`args` attribute.
123
124 .. versionadded:: 1.5.2
125
126 When an :exc:`EnvironmentError` exception is instantiated with a 3-tuple, the
127 first two items are available as above, while the third item is available on the
128 :attr:`filename` attribute. However, for backwards compatibility, the
129 :attr:`args` attribute contains only a 2-tuple of the first two constructor
130 arguments.
131
132 The :attr:`filename` attribute is ``None`` when this exception is created with
133 other than 3 arguments. The :attr:`errno` and :attr:`strerror` attributes are
134 also ``None`` when the instance was created with other than 2 or 3 arguments.
135 In this last case, :attr:`args` contains the verbatim constructor arguments as a
136 tuple.
137
138The following exceptions are the exceptions that are actually raised.
139
140
141.. exception:: AssertionError
142
143 .. index:: statement: assert
144
145 Raised when an :keyword:`assert` statement fails.
146
147
148.. exception:: AttributeError
149
Georg Brandlb19be572007-12-29 10:57:00 +0000150 Raised when an attribute reference (see :ref:`attribute-references`) or
151 assignment fails. (When an object does not support attribute references or
152 attribute assignments at all, :exc:`TypeError` is raised.)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000153
154
155.. exception:: EOFError
156
157 Raised when one of the built-in functions (:func:`input` or :func:`raw_input`)
158 hits an end-of-file condition (EOF) without reading any data. (N.B.: the
Georg Brandlb19be572007-12-29 10:57:00 +0000159 :meth:`file.read` and :meth:`file.readline` methods return an empty string
Georg Brandl8ec7f652007-08-15 14:28:01 +0000160 when they hit EOF.)
161
Georg Brandl8ec7f652007-08-15 14:28:01 +0000162
163.. exception:: FloatingPointError
164
165 Raised when a floating point operation fails. This exception is always defined,
166 but can only be raised when Python is configured with the
Éric Araujoa8132ec2010-12-16 03:53:53 +0000167 ``--with-fpectl`` option, or the :const:`WANT_SIGFPE_HANDLER` symbol is
Georg Brandl8ec7f652007-08-15 14:28:01 +0000168 defined in the :file:`pyconfig.h` file.
169
170
171.. exception:: GeneratorExit
172
Georg Brandlcf3fb252007-10-21 10:52:38 +0000173 Raise when a :term:`generator`\'s :meth:`close` method is called. It
Christian Heimes44eeaec2007-12-03 20:01:02 +0000174 directly inherits from :exc:`BaseException` instead of :exc:`StandardError` since
Georg Brandlcf3fb252007-10-21 10:52:38 +0000175 it is technically not an error.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000176
177 .. versionadded:: 2.5
178
Christian Heimes44eeaec2007-12-03 20:01:02 +0000179 .. versionchanged:: 2.6
180 Changed to inherit from :exc:`BaseException`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000181
182.. exception:: IOError
183
184 Raised when an I/O operation (such as a :keyword:`print` statement, the built-in
185 :func:`open` function or a method of a file object) fails for an I/O-related
186 reason, e.g., "file not found" or "disk full".
187
Georg Brandl8ec7f652007-08-15 14:28:01 +0000188 This class is derived from :exc:`EnvironmentError`. See the discussion above
189 for more information on exception instance attributes.
190
Gregory P. Smithe9fef692007-09-09 23:36:46 +0000191 .. versionchanged:: 2.6
192 Changed :exc:`socket.error` to use this as a base class.
193
Georg Brandl8ec7f652007-08-15 14:28:01 +0000194
195.. exception:: ImportError
196
197 Raised when an :keyword:`import` statement fails to find the module definition
198 or when a ``from ... import`` fails to find a name that is to be imported.
199
Georg Brandl8ec7f652007-08-15 14:28:01 +0000200
201.. exception:: IndexError
202
203 Raised when a sequence subscript is out of range. (Slice indices are silently
204 truncated to fall in the allowed range; if an index is not a plain integer,
205 :exc:`TypeError` is raised.)
206
Georg Brandlb19be572007-12-29 10:57:00 +0000207 .. XXX xref to sequences
Georg Brandl8ec7f652007-08-15 14:28:01 +0000208
209
210.. exception:: KeyError
211
212 Raised when a mapping (dictionary) key is not found in the set of existing keys.
213
Georg Brandlb19be572007-12-29 10:57:00 +0000214 .. XXX xref to mapping objects?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000215
216
217.. exception:: KeyboardInterrupt
218
219 Raised when the user hits the interrupt key (normally :kbd:`Control-C` or
220 :kbd:`Delete`). During execution, a check for interrupts is made regularly.
221 Interrupts typed when a built-in function :func:`input` or :func:`raw_input` is
222 waiting for input also raise this exception. The exception inherits from
223 :exc:`BaseException` so as to not be accidentally caught by code that catches
224 :exc:`Exception` and thus prevent the interpreter from exiting.
225
Georg Brandl8ec7f652007-08-15 14:28:01 +0000226 .. versionchanged:: 2.5
227 Changed to inherit from :exc:`BaseException`.
228
229
230.. exception:: MemoryError
231
232 Raised when an operation runs out of memory but the situation may still be
233 rescued (by deleting some objects). The associated value is a string indicating
234 what kind of (internal) operation ran out of memory. Note that because of the
235 underlying memory management architecture (C's :cfunc:`malloc` function), the
236 interpreter may not always be able to completely recover from this situation; it
237 nevertheless raises an exception so that a stack traceback can be printed, in
238 case a run-away program was the cause.
239
240
241.. exception:: NameError
242
243 Raised when a local or global name is not found. This applies only to
244 unqualified names. The associated value is an error message that includes the
245 name that could not be found.
246
247
248.. exception:: NotImplementedError
249
250 This exception is derived from :exc:`RuntimeError`. In user defined base
251 classes, abstract methods should raise this exception when they require derived
252 classes to override the method.
253
254 .. versionadded:: 1.5.2
255
256
257.. exception:: OSError
258
Georg Brandl57fe0f22008-01-12 10:53:29 +0000259 .. index:: module: errno
260
261 This exception is derived from :exc:`EnvironmentError`. It is raised when a
262 function returns a system-related error (not for illegal argument types or
263 other incidental errors). The :attr:`errno` attribute is a numeric error
264 code from :cdata:`errno`, and the :attr:`strerror` attribute is the
265 corresponding string, as would be printed by the C function :cfunc:`perror`.
266 See the module :mod:`errno`, which contains names for the error codes defined
267 by the underlying operating system.
268
269 For exceptions that involve a file system path (such as :func:`chdir` or
270 :func:`unlink`), the exception instance will contain a third attribute,
271 :attr:`filename`, which is the file name passed to the function.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000272
Georg Brandlfca4e1f2008-01-12 16:11:09 +0000273 .. versionadded:: 1.5.2
274
Georg Brandl8ec7f652007-08-15 14:28:01 +0000275
276.. exception:: OverflowError
277
278 Raised when the result of an arithmetic operation is too large to be
279 represented. This cannot occur for long integers (which would rather raise
Georg Brandle9135ba2008-05-11 10:55:59 +0000280 :exc:`MemoryError` than give up) and for most operations with plain integers,
281 which return a long integer instead. Because of the lack of standardization
282 of floating point exception handling in C, most floating point operations
283 also aren't checked.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000284
Georg Brandl8ec7f652007-08-15 14:28:01 +0000285
286.. exception:: ReferenceError
287
288 This exception is raised when a weak reference proxy, created by the
289 :func:`weakref.proxy` function, is used to access an attribute of the referent
290 after it has been garbage collected. For more information on weak references,
291 see the :mod:`weakref` module.
292
293 .. versionadded:: 2.2
294 Previously known as the :exc:`weakref.ReferenceError` exception.
295
296
297.. exception:: RuntimeError
298
299 Raised when an error is detected that doesn't fall in any of the other
300 categories. The associated value is a string indicating what precisely went
301 wrong. (This exception is mostly a relic from a previous version of the
302 interpreter; it is not used very much any more.)
303
304
305.. exception:: StopIteration
306
Georg Brandl9fa61bb2009-07-26 14:19:57 +0000307 Raised by an :term:`iterator`\'s :meth:`~iterator.next` method to signal that
308 there are no further values. This is derived from :exc:`Exception` rather
309 than :exc:`StandardError`, since this is not considered an error in its
310 normal application.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000311
312 .. versionadded:: 2.2
313
314
315.. exception:: SyntaxError
316
317 Raised when the parser encounters a syntax error. This may occur in an
318 :keyword:`import` statement, in an :keyword:`exec` statement, in a call to the
319 built-in function :func:`eval` or :func:`input`, or when reading the initial
320 script or standard input (also interactively).
321
Georg Brandl8ec7f652007-08-15 14:28:01 +0000322 Instances of this class have attributes :attr:`filename`, :attr:`lineno`,
323 :attr:`offset` and :attr:`text` for easier access to the details. :func:`str`
324 of the exception instance returns only the message.
325
326
Georg Brandl28dadd92011-02-25 10:50:32 +0000327.. exception:: IndentationError
328
329 Base class for syntax errors related to incorrect indentation. This is a
330 subclass of :exc:`SyntaxError`.
331
332
333.. exception:: TabError
334
335 Raised when indentation contains an inconsistent use of tabs and spaces.
336 This is a subclass of :exc:`IndentationError`.
337
338
Georg Brandl8ec7f652007-08-15 14:28:01 +0000339.. exception:: SystemError
340
341 Raised when the interpreter finds an internal error, but the situation does not
342 look so serious to cause it to abandon all hope. The associated value is a
343 string indicating what went wrong (in low-level terms).
344
345 You should report this to the author or maintainer of your Python interpreter.
346 Be sure to report the version of the Python interpreter (``sys.version``; it is
347 also printed at the start of an interactive Python session), the exact error
348 message (the exception's associated value) and if possible the source of the
349 program that triggered the error.
350
351
352.. exception:: SystemExit
353
354 This exception is raised by the :func:`sys.exit` function. When it is not
355 handled, the Python interpreter exits; no stack traceback is printed. If the
356 associated value is a plain integer, it specifies the system exit status (passed
357 to C's :cfunc:`exit` function); if it is ``None``, the exit status is zero; if
358 it has another type (such as a string), the object's value is printed and the
359 exit status is one.
360
Georg Brandl8ec7f652007-08-15 14:28:01 +0000361 Instances have an attribute :attr:`code` which is set to the proposed exit
362 status or error message (defaulting to ``None``). Also, this exception derives
363 directly from :exc:`BaseException` and not :exc:`StandardError`, since it is not
364 technically an error.
365
366 A call to :func:`sys.exit` is translated into an exception so that clean-up
367 handlers (:keyword:`finally` clauses of :keyword:`try` statements) can be
368 executed, and so that a debugger can execute a script without running the risk
369 of losing control. The :func:`os._exit` function can be used if it is
370 absolutely positively necessary to exit immediately (for example, in the child
371 process after a call to :func:`fork`).
372
373 The exception inherits from :exc:`BaseException` instead of :exc:`StandardError`
374 or :exc:`Exception` so that it is not accidentally caught by code that catches
375 :exc:`Exception`. This allows the exception to properly propagate up and cause
376 the interpreter to exit.
377
378 .. versionchanged:: 2.5
379 Changed to inherit from :exc:`BaseException`.
380
381
382.. exception:: TypeError
383
384 Raised when an operation or function is applied to an object of inappropriate
385 type. The associated value is a string giving details about the type mismatch.
386
387
388.. exception:: UnboundLocalError
389
390 Raised when a reference is made to a local variable in a function or method, but
391 no value has been bound to that variable. This is a subclass of
392 :exc:`NameError`.
393
394 .. versionadded:: 2.0
395
396
397.. exception:: UnicodeError
398
399 Raised when a Unicode-related encoding or decoding error occurs. It is a
400 subclass of :exc:`ValueError`.
401
402 .. versionadded:: 2.0
403
404
405.. exception:: UnicodeEncodeError
406
407 Raised when a Unicode-related error occurs during encoding. It is a subclass of
408 :exc:`UnicodeError`.
409
410 .. versionadded:: 2.3
411
412
413.. exception:: UnicodeDecodeError
414
415 Raised when a Unicode-related error occurs during decoding. It is a subclass of
416 :exc:`UnicodeError`.
417
418 .. versionadded:: 2.3
419
420
421.. exception:: UnicodeTranslateError
422
423 Raised when a Unicode-related error occurs during translating. It is a subclass
424 of :exc:`UnicodeError`.
425
426 .. versionadded:: 2.3
427
428
429.. exception:: ValueError
430
431 Raised when a built-in operation or function receives an argument that has the
432 right type but an inappropriate value, and the situation is not described by a
433 more precise exception such as :exc:`IndexError`.
434
435
Georg Brandl580d7c12009-02-18 00:31:36 +0000436.. exception:: VMSError
437
438 Only available on VMS. Raised when a VMS-specific error occurs.
439
440
Georg Brandl8ec7f652007-08-15 14:28:01 +0000441.. exception:: WindowsError
442
443 Raised when a Windows-specific error occurs or when the error number does not
444 correspond to an :cdata:`errno` value. The :attr:`winerror` and
445 :attr:`strerror` values are created from the return values of the
446 :cfunc:`GetLastError` and :cfunc:`FormatMessage` functions from the Windows
447 Platform API. The :attr:`errno` value maps the :attr:`winerror` value to
448 corresponding ``errno.h`` values. This is a subclass of :exc:`OSError`.
449
450 .. versionadded:: 2.0
451
452 .. versionchanged:: 2.5
453 Previous versions put the :cfunc:`GetLastError` codes into :attr:`errno`.
454
455
456.. exception:: ZeroDivisionError
457
458 Raised when the second argument of a division or modulo operation is zero. The
459 associated value is a string indicating the type of the operands and the
460 operation.
461
462The following exceptions are used as warning categories; see the :mod:`warnings`
463module for more information.
464
465
466.. exception:: Warning
467
468 Base class for warning categories.
469
470
471.. exception:: UserWarning
472
473 Base class for warnings generated by user code.
474
475
476.. exception:: DeprecationWarning
477
478 Base class for warnings about deprecated features.
479
480
481.. exception:: PendingDeprecationWarning
482
483 Base class for warnings about features which will be deprecated in the future.
484
485
486.. exception:: SyntaxWarning
487
488 Base class for warnings about dubious syntax
489
490
491.. exception:: RuntimeWarning
492
493 Base class for warnings about dubious runtime behavior.
494
495
496.. exception:: FutureWarning
497
498 Base class for warnings about constructs that will change semantically in the
499 future.
500
501
502.. exception:: ImportWarning
503
504 Base class for warnings about probable mistakes in module imports.
505
506 .. versionadded:: 2.5
507
508
509.. exception:: UnicodeWarning
510
511 Base class for warnings related to Unicode.
512
513 .. versionadded:: 2.5
514
Georg Brandl8ec7f652007-08-15 14:28:01 +0000515
Georg Brandl3cd0bed2009-06-30 16:18:55 +0000516Exception hierarchy
517-------------------
518
519The class hierarchy for built-in exceptions is:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000520
521.. literalinclude:: ../../Lib/test/exception_hierarchy.txt