blob: 6122d44568f0926033f02483d7125e9fa236a28e [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"
29indicating the detailed cause of the error. This may be a string or a tuple
30containing 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
49
50.. exception:: BaseException
51
52 The base class for all built-in exceptions. It is not meant to be directly
53 inherited by user-defined classes (for that use :exc:`Exception`). If
54 :func:`str` or :func:`unicode` is called on an instance of this class, the
55 representation of the argument(s) to the instance are returned or the emptry
56 string when there were no arguments. All arguments are stored in :attr:`args`
57 as a tuple.
58
59 .. versionadded:: 2.5
60
61
62.. exception:: Exception
63
64 All built-in, non-system-exiting exceptions are derived from this class. All
65 user-defined exceptions should also be derived from this class.
66
67 .. versionchanged:: 2.5
68 Changed to inherit from :exc:`BaseException`.
69
70
71.. exception:: StandardError
72
73 The base class for all built-in exceptions except :exc:`StopIteration`,
74 :exc:`GeneratorExit`, :exc:`KeyboardInterrupt` and :exc:`SystemExit`.
75 :exc:`StandardError` itself is derived from :exc:`Exception`.
76
77
78.. exception:: ArithmeticError
79
80 The base class for those built-in exceptions that are raised for various
81 arithmetic errors: :exc:`OverflowError`, :exc:`ZeroDivisionError`,
82 :exc:`FloatingPointError`.
83
84
85.. exception:: LookupError
86
87 The base class for the exceptions that are raised when a key or index used on a
88 mapping or sequence is invalid: :exc:`IndexError`, :exc:`KeyError`. This can be
89 raised directly by :func:`sys.setdefaultencoding`.
90
91
92.. exception:: EnvironmentError
93
94 The base class for exceptions that can occur outside the Python system:
95 :exc:`IOError`, :exc:`OSError`. When exceptions of this type are created with a
96 2-tuple, the first item is available on the instance's :attr:`errno` attribute
97 (it is assumed to be an error number), and the second item is available on the
98 :attr:`strerror` attribute (it is usually the associated error message). The
99 tuple itself is also available on the :attr:`args` attribute.
100
101 .. versionadded:: 1.5.2
102
103 When an :exc:`EnvironmentError` exception is instantiated with a 3-tuple, the
104 first two items are available as above, while the third item is available on the
105 :attr:`filename` attribute. However, for backwards compatibility, the
106 :attr:`args` attribute contains only a 2-tuple of the first two constructor
107 arguments.
108
109 The :attr:`filename` attribute is ``None`` when this exception is created with
110 other than 3 arguments. The :attr:`errno` and :attr:`strerror` attributes are
111 also ``None`` when the instance was created with other than 2 or 3 arguments.
112 In this last case, :attr:`args` contains the verbatim constructor arguments as a
113 tuple.
114
115The following exceptions are the exceptions that are actually raised.
116
117
118.. exception:: AssertionError
119
120 .. index:: statement: assert
121
122 Raised when an :keyword:`assert` statement fails.
123
124
125.. exception:: AttributeError
126
Georg Brandlb19be572007-12-29 10:57:00 +0000127 Raised when an attribute reference (see :ref:`attribute-references`) or
128 assignment fails. (When an object does not support attribute references or
129 attribute assignments at all, :exc:`TypeError` is raised.)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000130
131
132.. exception:: EOFError
133
134 Raised when one of the built-in functions (:func:`input` or :func:`raw_input`)
135 hits an end-of-file condition (EOF) without reading any data. (N.B.: the
Georg Brandlb19be572007-12-29 10:57:00 +0000136 :meth:`file.read` and :meth:`file.readline` methods return an empty string
Georg Brandl8ec7f652007-08-15 14:28:01 +0000137 when they hit EOF.)
138
Georg Brandl8ec7f652007-08-15 14:28:01 +0000139
140.. exception:: FloatingPointError
141
142 Raised when a floating point operation fails. This exception is always defined,
143 but can only be raised when Python is configured with the
144 :option:`--with-fpectl` option, or the :const:`WANT_SIGFPE_HANDLER` symbol is
145 defined in the :file:`pyconfig.h` file.
146
147
148.. exception:: GeneratorExit
149
Georg Brandlcf3fb252007-10-21 10:52:38 +0000150 Raise when a :term:`generator`\'s :meth:`close` method is called. It
Christian Heimes44eeaec2007-12-03 20:01:02 +0000151 directly inherits from :exc:`BaseException` instead of :exc:`StandardError` since
Georg Brandlcf3fb252007-10-21 10:52:38 +0000152 it is technically not an error.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000153
154 .. versionadded:: 2.5
155
Christian Heimes44eeaec2007-12-03 20:01:02 +0000156 .. versionchanged:: 2.6
157 Changed to inherit from :exc:`BaseException`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000158
159.. exception:: IOError
160
161 Raised when an I/O operation (such as a :keyword:`print` statement, the built-in
162 :func:`open` function or a method of a file object) fails for an I/O-related
163 reason, e.g., "file not found" or "disk full".
164
Georg Brandl8ec7f652007-08-15 14:28:01 +0000165 This class is derived from :exc:`EnvironmentError`. See the discussion above
166 for more information on exception instance attributes.
167
Gregory P. Smithe9fef692007-09-09 23:36:46 +0000168 .. versionchanged:: 2.6
169 Changed :exc:`socket.error` to use this as a base class.
170
Georg Brandl8ec7f652007-08-15 14:28:01 +0000171
172.. exception:: ImportError
173
174 Raised when an :keyword:`import` statement fails to find the module definition
175 or when a ``from ... import`` fails to find a name that is to be imported.
176
Georg Brandl8ec7f652007-08-15 14:28:01 +0000177
178.. exception:: IndexError
179
180 Raised when a sequence subscript is out of range. (Slice indices are silently
181 truncated to fall in the allowed range; if an index is not a plain integer,
182 :exc:`TypeError` is raised.)
183
Georg Brandlb19be572007-12-29 10:57:00 +0000184 .. XXX xref to sequences
Georg Brandl8ec7f652007-08-15 14:28:01 +0000185
186
187.. exception:: KeyError
188
189 Raised when a mapping (dictionary) key is not found in the set of existing keys.
190
Georg Brandlb19be572007-12-29 10:57:00 +0000191 .. XXX xref to mapping objects?
Georg Brandl8ec7f652007-08-15 14:28:01 +0000192
193
194.. exception:: KeyboardInterrupt
195
196 Raised when the user hits the interrupt key (normally :kbd:`Control-C` or
197 :kbd:`Delete`). During execution, a check for interrupts is made regularly.
198 Interrupts typed when a built-in function :func:`input` or :func:`raw_input` is
199 waiting for input also raise this exception. The exception inherits from
200 :exc:`BaseException` so as to not be accidentally caught by code that catches
201 :exc:`Exception` and thus prevent the interpreter from exiting.
202
Georg Brandl8ec7f652007-08-15 14:28:01 +0000203 .. versionchanged:: 2.5
204 Changed to inherit from :exc:`BaseException`.
205
206
207.. exception:: MemoryError
208
209 Raised when an operation runs out of memory but the situation may still be
210 rescued (by deleting some objects). The associated value is a string indicating
211 what kind of (internal) operation ran out of memory. Note that because of the
212 underlying memory management architecture (C's :cfunc:`malloc` function), the
213 interpreter may not always be able to completely recover from this situation; it
214 nevertheless raises an exception so that a stack traceback can be printed, in
215 case a run-away program was the cause.
216
217
218.. exception:: NameError
219
220 Raised when a local or global name is not found. This applies only to
221 unqualified names. The associated value is an error message that includes the
222 name that could not be found.
223
224
225.. exception:: NotImplementedError
226
227 This exception is derived from :exc:`RuntimeError`. In user defined base
228 classes, abstract methods should raise this exception when they require derived
229 classes to override the method.
230
231 .. versionadded:: 1.5.2
232
233
234.. exception:: OSError
235
236 This class is derived from :exc:`EnvironmentError` and is used primarily as the
237 :mod:`os` module's ``os.error`` exception. See :exc:`EnvironmentError` above for
238 a description of the possible associated values.
239
Georg Brandl8ec7f652007-08-15 14:28:01 +0000240 .. versionadded:: 1.5.2
241
242
243.. exception:: OverflowError
244
245 Raised when the result of an arithmetic operation is too large to be
246 represented. This cannot occur for long integers (which would rather raise
247 :exc:`MemoryError` than give up). Because of the lack of standardization of
248 floating point exception handling in C, most floating point operations also
249 aren't checked. For plain integers, all operations that can overflow are
250 checked except left shift, where typical applications prefer to drop bits than
251 raise an exception.
252
Georg Brandl8ec7f652007-08-15 14:28:01 +0000253
254.. exception:: ReferenceError
255
256 This exception is raised when a weak reference proxy, created by the
257 :func:`weakref.proxy` function, is used to access an attribute of the referent
258 after it has been garbage collected. For more information on weak references,
259 see the :mod:`weakref` module.
260
261 .. versionadded:: 2.2
262 Previously known as the :exc:`weakref.ReferenceError` exception.
263
264
265.. exception:: RuntimeError
266
267 Raised when an error is detected that doesn't fall in any of the other
268 categories. The associated value is a string indicating what precisely went
269 wrong. (This exception is mostly a relic from a previous version of the
270 interpreter; it is not used very much any more.)
271
272
273.. exception:: StopIteration
274
Georg Brandle7a09902007-10-21 12:10:28 +0000275 Raised by an :term:`iterator`\'s :meth:`next` method to signal that there are
276 no further values. This is derived from :exc:`Exception` rather than
277 :exc:`StandardError`, since this is not considered an error in its normal
278 application.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000279
280 .. versionadded:: 2.2
281
282
283.. exception:: SyntaxError
284
285 Raised when the parser encounters a syntax error. This may occur in an
286 :keyword:`import` statement, in an :keyword:`exec` statement, in a call to the
287 built-in function :func:`eval` or :func:`input`, or when reading the initial
288 script or standard input (also interactively).
289
Georg Brandl8ec7f652007-08-15 14:28:01 +0000290 Instances of this class have attributes :attr:`filename`, :attr:`lineno`,
291 :attr:`offset` and :attr:`text` for easier access to the details. :func:`str`
292 of the exception instance returns only the message.
293
294
295.. exception:: SystemError
296
297 Raised when the interpreter finds an internal error, but the situation does not
298 look so serious to cause it to abandon all hope. The associated value is a
299 string indicating what went wrong (in low-level terms).
300
301 You should report this to the author or maintainer of your Python interpreter.
302 Be sure to report the version of the Python interpreter (``sys.version``; it is
303 also printed at the start of an interactive Python session), the exact error
304 message (the exception's associated value) and if possible the source of the
305 program that triggered the error.
306
307
308.. exception:: SystemExit
309
310 This exception is raised by the :func:`sys.exit` function. When it is not
311 handled, the Python interpreter exits; no stack traceback is printed. If the
312 associated value is a plain integer, it specifies the system exit status (passed
313 to C's :cfunc:`exit` function); if it is ``None``, the exit status is zero; if
314 it has another type (such as a string), the object's value is printed and the
315 exit status is one.
316
Georg Brandl8ec7f652007-08-15 14:28:01 +0000317 Instances have an attribute :attr:`code` which is set to the proposed exit
318 status or error message (defaulting to ``None``). Also, this exception derives
319 directly from :exc:`BaseException` and not :exc:`StandardError`, since it is not
320 technically an error.
321
322 A call to :func:`sys.exit` is translated into an exception so that clean-up
323 handlers (:keyword:`finally` clauses of :keyword:`try` statements) can be
324 executed, and so that a debugger can execute a script without running the risk
325 of losing control. The :func:`os._exit` function can be used if it is
326 absolutely positively necessary to exit immediately (for example, in the child
327 process after a call to :func:`fork`).
328
329 The exception inherits from :exc:`BaseException` instead of :exc:`StandardError`
330 or :exc:`Exception` so that it is not accidentally caught by code that catches
331 :exc:`Exception`. This allows the exception to properly propagate up and cause
332 the interpreter to exit.
333
334 .. versionchanged:: 2.5
335 Changed to inherit from :exc:`BaseException`.
336
337
338.. exception:: TypeError
339
340 Raised when an operation or function is applied to an object of inappropriate
341 type. The associated value is a string giving details about the type mismatch.
342
343
344.. exception:: UnboundLocalError
345
346 Raised when a reference is made to a local variable in a function or method, but
347 no value has been bound to that variable. This is a subclass of
348 :exc:`NameError`.
349
350 .. versionadded:: 2.0
351
352
353.. exception:: UnicodeError
354
355 Raised when a Unicode-related encoding or decoding error occurs. It is a
356 subclass of :exc:`ValueError`.
357
358 .. versionadded:: 2.0
359
360
361.. exception:: UnicodeEncodeError
362
363 Raised when a Unicode-related error occurs during encoding. It is a subclass of
364 :exc:`UnicodeError`.
365
366 .. versionadded:: 2.3
367
368
369.. exception:: UnicodeDecodeError
370
371 Raised when a Unicode-related error occurs during decoding. It is a subclass of
372 :exc:`UnicodeError`.
373
374 .. versionadded:: 2.3
375
376
377.. exception:: UnicodeTranslateError
378
379 Raised when a Unicode-related error occurs during translating. It is a subclass
380 of :exc:`UnicodeError`.
381
382 .. versionadded:: 2.3
383
384
385.. exception:: ValueError
386
387 Raised when a built-in operation or function receives an argument that has the
388 right type but an inappropriate value, and the situation is not described by a
389 more precise exception such as :exc:`IndexError`.
390
391
392.. exception:: WindowsError
393
394 Raised when a Windows-specific error occurs or when the error number does not
395 correspond to an :cdata:`errno` value. The :attr:`winerror` and
396 :attr:`strerror` values are created from the return values of the
397 :cfunc:`GetLastError` and :cfunc:`FormatMessage` functions from the Windows
398 Platform API. The :attr:`errno` value maps the :attr:`winerror` value to
399 corresponding ``errno.h`` values. This is a subclass of :exc:`OSError`.
400
401 .. versionadded:: 2.0
402
403 .. versionchanged:: 2.5
404 Previous versions put the :cfunc:`GetLastError` codes into :attr:`errno`.
405
406
407.. exception:: ZeroDivisionError
408
409 Raised when the second argument of a division or modulo operation is zero. The
410 associated value is a string indicating the type of the operands and the
411 operation.
412
413The following exceptions are used as warning categories; see the :mod:`warnings`
414module for more information.
415
416
417.. exception:: Warning
418
419 Base class for warning categories.
420
421
422.. exception:: UserWarning
423
424 Base class for warnings generated by user code.
425
426
427.. exception:: DeprecationWarning
428
429 Base class for warnings about deprecated features.
430
431
432.. exception:: PendingDeprecationWarning
433
434 Base class for warnings about features which will be deprecated in the future.
435
436
437.. exception:: SyntaxWarning
438
439 Base class for warnings about dubious syntax
440
441
442.. exception:: RuntimeWarning
443
444 Base class for warnings about dubious runtime behavior.
445
446
447.. exception:: FutureWarning
448
449 Base class for warnings about constructs that will change semantically in the
450 future.
451
452
453.. exception:: ImportWarning
454
455 Base class for warnings about probable mistakes in module imports.
456
457 .. versionadded:: 2.5
458
459
460.. exception:: UnicodeWarning
461
462 Base class for warnings related to Unicode.
463
464 .. versionadded:: 2.5
465
466The class hierarchy for built-in exceptions is:
467
468
469.. literalinclude:: ../../Lib/test/exception_hierarchy.txt