blob: 9081cf797ab3e03985e39bac77338be2296db6e0 [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
127 Raised when an attribute reference or assignment fails. (When an object does
128 not support attribute references or attribute assignments at all,
129 :exc:`TypeError` is raised.)
130
131 .. % xref to attribute reference?
132
133
134.. exception:: EOFError
135
136 Raised when one of the built-in functions (:func:`input` or :func:`raw_input`)
137 hits an end-of-file condition (EOF) without reading any data. (N.B.: the
138 :meth:`read` and :meth:`readline` methods of file objects return an empty string
139 when they hit EOF.)
140
141 .. % XXXJH xrefs here
142 .. % XXXJH xrefs here
143
144
145.. exception:: FloatingPointError
146
147 Raised when a floating point operation fails. This exception is always defined,
148 but can only be raised when Python is configured with the
149 :option:`--with-fpectl` option, or the :const:`WANT_SIGFPE_HANDLER` symbol is
150 defined in the :file:`pyconfig.h` file.
151
152
153.. exception:: GeneratorExit
154
155 Raise when a generator's :meth:`close` method is called. It directly inherits
156 from :exc:`Exception` instead of :exc:`StandardError` since it is technically
157 not an error.
158
159 .. versionadded:: 2.5
160
161
162.. exception:: IOError
163
164 Raised when an I/O operation (such as a :keyword:`print` statement, the built-in
165 :func:`open` function or a method of a file object) fails for an I/O-related
166 reason, e.g., "file not found" or "disk full".
167
168 .. % XXXJH xrefs here
169
170 This class is derived from :exc:`EnvironmentError`. See the discussion above
171 for more information on exception instance attributes.
172
173
174.. exception:: ImportError
175
176 Raised when an :keyword:`import` statement fails to find the module definition
177 or when a ``from ... import`` fails to find a name that is to be imported.
178
179 .. % XXXJH xref to import statement?
180
181
182.. exception:: IndexError
183
184 Raised when a sequence subscript is out of range. (Slice indices are silently
185 truncated to fall in the allowed range; if an index is not a plain integer,
186 :exc:`TypeError` is raised.)
187
188 .. % XXXJH xref to sequences
189
190
191.. exception:: KeyError
192
193 Raised when a mapping (dictionary) key is not found in the set of existing keys.
194
195 .. % XXXJH xref to mapping objects?
196
197
198.. exception:: KeyboardInterrupt
199
200 Raised when the user hits the interrupt key (normally :kbd:`Control-C` or
201 :kbd:`Delete`). During execution, a check for interrupts is made regularly.
202 Interrupts typed when a built-in function :func:`input` or :func:`raw_input` is
203 waiting for input also raise this exception. The exception inherits from
204 :exc:`BaseException` so as to not be accidentally caught by code that catches
205 :exc:`Exception` and thus prevent the interpreter from exiting.
206
207 .. % XXX(hylton) xrefs here
208
209 .. versionchanged:: 2.5
210 Changed to inherit from :exc:`BaseException`.
211
212
213.. exception:: MemoryError
214
215 Raised when an operation runs out of memory but the situation may still be
216 rescued (by deleting some objects). The associated value is a string indicating
217 what kind of (internal) operation ran out of memory. Note that because of the
218 underlying memory management architecture (C's :cfunc:`malloc` function), the
219 interpreter may not always be able to completely recover from this situation; it
220 nevertheless raises an exception so that a stack traceback can be printed, in
221 case a run-away program was the cause.
222
223
224.. exception:: NameError
225
226 Raised when a local or global name is not found. This applies only to
227 unqualified names. The associated value is an error message that includes the
228 name that could not be found.
229
230
231.. exception:: NotImplementedError
232
233 This exception is derived from :exc:`RuntimeError`. In user defined base
234 classes, abstract methods should raise this exception when they require derived
235 classes to override the method.
236
237 .. versionadded:: 1.5.2
238
239
240.. exception:: OSError
241
242 This class is derived from :exc:`EnvironmentError` and is used primarily as the
243 :mod:`os` module's ``os.error`` exception. See :exc:`EnvironmentError` above for
244 a description of the possible associated values.
245
246 .. % xref for os module
247
248 .. versionadded:: 1.5.2
249
250
251.. exception:: OverflowError
252
253 Raised when the result of an arithmetic operation is too large to be
254 represented. This cannot occur for long integers (which would rather raise
255 :exc:`MemoryError` than give up). Because of the lack of standardization of
256 floating point exception handling in C, most floating point operations also
257 aren't checked. For plain integers, all operations that can overflow are
258 checked except left shift, where typical applications prefer to drop bits than
259 raise an exception.
260
261 .. % XXXJH reference to long's and/or int's?
262
263
264.. exception:: ReferenceError
265
266 This exception is raised when a weak reference proxy, created by the
267 :func:`weakref.proxy` function, is used to access an attribute of the referent
268 after it has been garbage collected. For more information on weak references,
269 see the :mod:`weakref` module.
270
271 .. versionadded:: 2.2
272 Previously known as the :exc:`weakref.ReferenceError` exception.
273
274
275.. exception:: RuntimeError
276
277 Raised when an error is detected that doesn't fall in any of the other
278 categories. The associated value is a string indicating what precisely went
279 wrong. (This exception is mostly a relic from a previous version of the
280 interpreter; it is not used very much any more.)
281
282
283.. exception:: StopIteration
284
285 Raised by an iterator's :meth:`next` method to signal that there are no further
286 values. This is derived from :exc:`Exception` rather than :exc:`StandardError`,
287 since this is not considered an error in its normal application.
288
289 .. versionadded:: 2.2
290
291
292.. exception:: SyntaxError
293
294 Raised when the parser encounters a syntax error. This may occur in an
295 :keyword:`import` statement, in an :keyword:`exec` statement, in a call to the
296 built-in function :func:`eval` or :func:`input`, or when reading the initial
297 script or standard input (also interactively).
298
299 .. % XXXJH xref to these functions?
300
301 Instances of this class have attributes :attr:`filename`, :attr:`lineno`,
302 :attr:`offset` and :attr:`text` for easier access to the details. :func:`str`
303 of the exception instance returns only the message.
304
305
306.. exception:: SystemError
307
308 Raised when the interpreter finds an internal error, but the situation does not
309 look so serious to cause it to abandon all hope. The associated value is a
310 string indicating what went wrong (in low-level terms).
311
312 You should report this to the author or maintainer of your Python interpreter.
313 Be sure to report the version of the Python interpreter (``sys.version``; it is
314 also printed at the start of an interactive Python session), the exact error
315 message (the exception's associated value) and if possible the source of the
316 program that triggered the error.
317
318
319.. exception:: SystemExit
320
321 This exception is raised by the :func:`sys.exit` function. When it is not
322 handled, the Python interpreter exits; no stack traceback is printed. If the
323 associated value is a plain integer, it specifies the system exit status (passed
324 to C's :cfunc:`exit` function); if it is ``None``, the exit status is zero; if
325 it has another type (such as a string), the object's value is printed and the
326 exit status is one.
327
328 .. % XXX(hylton) xref to module sys?
329
330 Instances have an attribute :attr:`code` which is set to the proposed exit
331 status or error message (defaulting to ``None``). Also, this exception derives
332 directly from :exc:`BaseException` and not :exc:`StandardError`, since it is not
333 technically an error.
334
335 A call to :func:`sys.exit` is translated into an exception so that clean-up
336 handlers (:keyword:`finally` clauses of :keyword:`try` statements) can be
337 executed, and so that a debugger can execute a script without running the risk
338 of losing control. The :func:`os._exit` function can be used if it is
339 absolutely positively necessary to exit immediately (for example, in the child
340 process after a call to :func:`fork`).
341
342 The exception inherits from :exc:`BaseException` instead of :exc:`StandardError`
343 or :exc:`Exception` so that it is not accidentally caught by code that catches
344 :exc:`Exception`. This allows the exception to properly propagate up and cause
345 the interpreter to exit.
346
347 .. versionchanged:: 2.5
348 Changed to inherit from :exc:`BaseException`.
349
350
351.. exception:: TypeError
352
353 Raised when an operation or function is applied to an object of inappropriate
354 type. The associated value is a string giving details about the type mismatch.
355
356
357.. exception:: UnboundLocalError
358
359 Raised when a reference is made to a local variable in a function or method, but
360 no value has been bound to that variable. This is a subclass of
361 :exc:`NameError`.
362
363 .. versionadded:: 2.0
364
365
366.. exception:: UnicodeError
367
368 Raised when a Unicode-related encoding or decoding error occurs. It is a
369 subclass of :exc:`ValueError`.
370
371 .. versionadded:: 2.0
372
373
374.. exception:: UnicodeEncodeError
375
376 Raised when a Unicode-related error occurs during encoding. It is a subclass of
377 :exc:`UnicodeError`.
378
379 .. versionadded:: 2.3
380
381
382.. exception:: UnicodeDecodeError
383
384 Raised when a Unicode-related error occurs during decoding. It is a subclass of
385 :exc:`UnicodeError`.
386
387 .. versionadded:: 2.3
388
389
390.. exception:: UnicodeTranslateError
391
392 Raised when a Unicode-related error occurs during translating. It is a subclass
393 of :exc:`UnicodeError`.
394
395 .. versionadded:: 2.3
396
397
398.. exception:: ValueError
399
400 Raised when a built-in operation or function receives an argument that has the
401 right type but an inappropriate value, and the situation is not described by a
402 more precise exception such as :exc:`IndexError`.
403
404
405.. exception:: WindowsError
406
407 Raised when a Windows-specific error occurs or when the error number does not
408 correspond to an :cdata:`errno` value. The :attr:`winerror` and
409 :attr:`strerror` values are created from the return values of the
410 :cfunc:`GetLastError` and :cfunc:`FormatMessage` functions from the Windows
411 Platform API. The :attr:`errno` value maps the :attr:`winerror` value to
412 corresponding ``errno.h`` values. This is a subclass of :exc:`OSError`.
413
414 .. versionadded:: 2.0
415
416 .. versionchanged:: 2.5
417 Previous versions put the :cfunc:`GetLastError` codes into :attr:`errno`.
418
419
420.. exception:: ZeroDivisionError
421
422 Raised when the second argument of a division or modulo operation is zero. The
423 associated value is a string indicating the type of the operands and the
424 operation.
425
426The following exceptions are used as warning categories; see the :mod:`warnings`
427module for more information.
428
429
430.. exception:: Warning
431
432 Base class for warning categories.
433
434
435.. exception:: UserWarning
436
437 Base class for warnings generated by user code.
438
439
440.. exception:: DeprecationWarning
441
442 Base class for warnings about deprecated features.
443
444
445.. exception:: PendingDeprecationWarning
446
447 Base class for warnings about features which will be deprecated in the future.
448
449
450.. exception:: SyntaxWarning
451
452 Base class for warnings about dubious syntax
453
454
455.. exception:: RuntimeWarning
456
457 Base class for warnings about dubious runtime behavior.
458
459
460.. exception:: FutureWarning
461
462 Base class for warnings about constructs that will change semantically in the
463 future.
464
465
466.. exception:: ImportWarning
467
468 Base class for warnings about probable mistakes in module imports.
469
470 .. versionadded:: 2.5
471
472
473.. exception:: UnicodeWarning
474
475 Base class for warnings related to Unicode.
476
477 .. versionadded:: 2.5
478
479The class hierarchy for built-in exceptions is:
480
481
482.. literalinclude:: ../../Lib/test/exception_hierarchy.txt