blob: 989eb9d00cb4002a2ad3b0874cfe7ffe8add3a15 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +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
Georg Brandl116aa622007-08-15 14:28:22 +000059
60.. exception:: Exception
61
62 All built-in, non-system-exiting exceptions are derived from this class. All
63 user-defined exceptions should also be derived from this class.
64
Georg Brandl116aa622007-08-15 14:28:22 +000065
66.. exception:: ArithmeticError
67
68 The base class for those built-in exceptions that are raised for various
69 arithmetic errors: :exc:`OverflowError`, :exc:`ZeroDivisionError`,
70 :exc:`FloatingPointError`.
71
72
73.. exception:: LookupError
74
75 The base class for the exceptions that are raised when a key or index used on a
76 mapping or sequence is invalid: :exc:`IndexError`, :exc:`KeyError`. This can be
77 raised directly by :func:`sys.setdefaultencoding`.
78
79
80.. exception:: EnvironmentError
81
82 The base class for exceptions that can occur outside the Python system:
83 :exc:`IOError`, :exc:`OSError`. When exceptions of this type are created with a
84 2-tuple, the first item is available on the instance's :attr:`errno` attribute
85 (it is assumed to be an error number), and the second item is available on the
86 :attr:`strerror` attribute (it is usually the associated error message). The
87 tuple itself is also available on the :attr:`args` attribute.
88
Georg Brandl116aa622007-08-15 14:28:22 +000089 When an :exc:`EnvironmentError` exception is instantiated with a 3-tuple, the
90 first two items are available as above, while the third item is available on the
91 :attr:`filename` attribute. However, for backwards compatibility, the
92 :attr:`args` attribute contains only a 2-tuple of the first two constructor
93 arguments.
94
95 The :attr:`filename` attribute is ``None`` when this exception is created with
96 other than 3 arguments. The :attr:`errno` and :attr:`strerror` attributes are
97 also ``None`` when the instance was created with other than 2 or 3 arguments.
98 In this last case, :attr:`args` contains the verbatim constructor arguments as a
99 tuple.
100
101The following exceptions are the exceptions that are actually raised.
102
103
104.. exception:: AssertionError
105
106 .. index:: statement: assert
107
108 Raised when an :keyword:`assert` statement fails.
109
110
111.. exception:: AttributeError
112
113 Raised when an attribute reference or assignment fails. (When an object does
114 not support attribute references or attribute assignments at all,
115 :exc:`TypeError` is raised.)
116
117 .. % xref to attribute reference?
118
119
120.. exception:: EOFError
121
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000122 Raised when attempting to read beyond the end of a file. (N.B.: the
123 :meth:`file.read` and :meth:`file.readline` methods return an empty string
124 when they hit EOF.)
Georg Brandl116aa622007-08-15 14:28:22 +0000125
126
127.. exception:: FloatingPointError
128
129 Raised when a floating point operation fails. This exception is always defined,
130 but can only be raised when Python is configured with the
131 :option:`--with-fpectl` option, or the :const:`WANT_SIGFPE_HANDLER` symbol is
132 defined in the :file:`pyconfig.h` file.
133
134
135.. exception:: GeneratorExit
136
137 Raise when a generator's :meth:`close` method is called.
138
Georg Brandl116aa622007-08-15 14:28:22 +0000139
140.. exception:: IOError
141
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000142 Raised when an I/O operation (such as the built-in :func:`print` or
143 :func:`open` functions or a method of a file object) fails for an I/O-related
Georg Brandl116aa622007-08-15 14:28:22 +0000144 reason, e.g., "file not found" or "disk full".
145
Georg Brandl116aa622007-08-15 14:28:22 +0000146 This class is derived from :exc:`EnvironmentError`. See the discussion above
147 for more information on exception instance attributes.
148
149
150.. exception:: ImportError
151
152 Raised when an :keyword:`import` statement fails to find the module definition
153 or when a ``from ... import`` fails to find a name that is to be imported.
154
Georg Brandl116aa622007-08-15 14:28:22 +0000155
156.. exception:: IndexError
157
158 Raised when a sequence subscript is out of range. (Slice indices are silently
159 truncated to fall in the allowed range; if an index is not a plain integer,
160 :exc:`TypeError` is raised.)
161
162 .. % XXXJH xref to sequences
163
164
165.. exception:: KeyError
166
167 Raised when a mapping (dictionary) key is not found in the set of existing keys.
168
169 .. % XXXJH xref to mapping objects?
170
171
172.. exception:: KeyboardInterrupt
173
174 Raised when the user hits the interrupt key (normally :kbd:`Control-C` or
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000175 :kbd:`Delete`). During execution, a check for interrupts is made
176 regularly. The exception inherits from :exc:`BaseException` so as to not be
177 accidentally caught by code that catches :exc:`Exception` and thus prevent
178 the interpreter from exiting.
Georg Brandl116aa622007-08-15 14:28:22 +0000179
Georg Brandl116aa622007-08-15 14:28:22 +0000180
181.. exception:: MemoryError
182
183 Raised when an operation runs out of memory but the situation may still be
184 rescued (by deleting some objects). The associated value is a string indicating
185 what kind of (internal) operation ran out of memory. Note that because of the
186 underlying memory management architecture (C's :cfunc:`malloc` function), the
187 interpreter may not always be able to completely recover from this situation; it
188 nevertheless raises an exception so that a stack traceback can be printed, in
189 case a run-away program was the cause.
190
191
192.. exception:: NameError
193
194 Raised when a local or global name is not found. This applies only to
195 unqualified names. The associated value is an error message that includes the
196 name that could not be found.
197
198
199.. exception:: NotImplementedError
200
201 This exception is derived from :exc:`RuntimeError`. In user defined base
202 classes, abstract methods should raise this exception when they require derived
203 classes to override the method.
204
Georg Brandl116aa622007-08-15 14:28:22 +0000205
206.. exception:: OSError
207
208 This class is derived from :exc:`EnvironmentError` and is used primarily as the
209 :mod:`os` module's ``os.error`` exception. See :exc:`EnvironmentError` above for
210 a description of the possible associated values.
211
Georg Brandl116aa622007-08-15 14:28:22 +0000212
213.. exception:: OverflowError
214
215 Raised when the result of an arithmetic operation is too large to be
216 represented. This cannot occur for long integers (which would rather raise
217 :exc:`MemoryError` than give up). Because of the lack of standardization of
218 floating point exception handling in C, most floating point operations also
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000219 aren't checked.
Georg Brandl116aa622007-08-15 14:28:22 +0000220
221
222.. exception:: ReferenceError
223
224 This exception is raised when a weak reference proxy, created by the
225 :func:`weakref.proxy` function, is used to access an attribute of the referent
226 after it has been garbage collected. For more information on weak references,
227 see the :mod:`weakref` module.
228
Georg Brandl116aa622007-08-15 14:28:22 +0000229
230.. exception:: RuntimeError
231
232 Raised when an error is detected that doesn't fall in any of the other
233 categories. The associated value is a string indicating what precisely went
234 wrong. (This exception is mostly a relic from a previous version of the
235 interpreter; it is not used very much any more.)
236
237
238.. exception:: StopIteration
239
240 Raised by builtin :func:`next` and an iterator's :meth:`__next__` method to
241 signal that there are no further values.
242
Georg Brandl116aa622007-08-15 14:28:22 +0000243
244.. exception:: SyntaxError
245
246 Raised when the parser encounters a syntax error. This may occur in an
247 :keyword:`import` statement, in a call to the built-in functions :func:`exec`
248 or :func:`eval`, or when reading the initial script or standard input
249 (also interactively).
250
Georg Brandl116aa622007-08-15 14:28:22 +0000251 Instances of this class have attributes :attr:`filename`, :attr:`lineno`,
252 :attr:`offset` and :attr:`text` for easier access to the details. :func:`str`
253 of the exception instance returns only the message.
254
255
256.. exception:: SystemError
257
258 Raised when the interpreter finds an internal error, but the situation does not
259 look so serious to cause it to abandon all hope. The associated value is a
260 string indicating what went wrong (in low-level terms).
261
262 You should report this to the author or maintainer of your Python interpreter.
263 Be sure to report the version of the Python interpreter (``sys.version``; it is
264 also printed at the start of an interactive Python session), the exact error
265 message (the exception's associated value) and if possible the source of the
266 program that triggered the error.
267
268
269.. exception:: SystemExit
270
271 This exception is raised by the :func:`sys.exit` function. When it is not
272 handled, the Python interpreter exits; no stack traceback is printed. If the
273 associated value is a plain integer, it specifies the system exit status (passed
274 to C's :cfunc:`exit` function); if it is ``None``, the exit status is zero; if
275 it has another type (such as a string), the object's value is printed and the
276 exit status is one.
277
Georg Brandl116aa622007-08-15 14:28:22 +0000278 Instances have an attribute :attr:`code` which is set to the proposed exit
279 status or error message (defaulting to ``None``). Also, this exception derives
280 directly from :exc:`BaseException` and not :exc:`Exception`, since it is not
281 technically an error.
282
283 A call to :func:`sys.exit` is translated into an exception so that clean-up
284 handlers (:keyword:`finally` clauses of :keyword:`try` statements) can be
285 executed, and so that a debugger can execute a script without running the risk
286 of losing control. The :func:`os._exit` function can be used if it is
287 absolutely positively necessary to exit immediately (for example, in the child
288 process after a call to :func:`fork`).
289
290 The exception inherits from :exc:`BaseException` instead of :exc:`Exception` so
291 that it is not accidentally caught by code that catches :exc:`Exception`. This
292 allows the exception to properly propagate up and cause the interpreter to exit.
293
Georg Brandl116aa622007-08-15 14:28:22 +0000294
295.. exception:: TypeError
296
297 Raised when an operation or function is applied to an object of inappropriate
298 type. The associated value is a string giving details about the type mismatch.
299
300
301.. exception:: UnboundLocalError
302
303 Raised when a reference is made to a local variable in a function or method, but
304 no value has been bound to that variable. This is a subclass of
305 :exc:`NameError`.
306
Georg Brandl116aa622007-08-15 14:28:22 +0000307
308.. exception:: UnicodeError
309
310 Raised when a Unicode-related encoding or decoding error occurs. It is a
311 subclass of :exc:`ValueError`.
312
Georg Brandl116aa622007-08-15 14:28:22 +0000313
314.. exception:: UnicodeEncodeError
315
316 Raised when a Unicode-related error occurs during encoding. It is a subclass of
317 :exc:`UnicodeError`.
318
Georg Brandl116aa622007-08-15 14:28:22 +0000319
320.. exception:: UnicodeDecodeError
321
322 Raised when a Unicode-related error occurs during decoding. It is a subclass of
323 :exc:`UnicodeError`.
324
Georg Brandl116aa622007-08-15 14:28:22 +0000325
326.. exception:: UnicodeTranslateError
327
328 Raised when a Unicode-related error occurs during translating. It is a subclass
329 of :exc:`UnicodeError`.
330
Georg Brandl116aa622007-08-15 14:28:22 +0000331
332.. exception:: ValueError
333
334 Raised when a built-in operation or function receives an argument that has the
335 right type but an inappropriate value, and the situation is not described by a
336 more precise exception such as :exc:`IndexError`.
337
338
339.. exception:: WindowsError
340
341 Raised when a Windows-specific error occurs or when the error number does not
342 correspond to an :cdata:`errno` value. The :attr:`winerror` and
343 :attr:`strerror` values are created from the return values of the
344 :cfunc:`GetLastError` and :cfunc:`FormatMessage` functions from the Windows
345 Platform API. The :attr:`errno` value maps the :attr:`winerror` value to
346 corresponding ``errno.h`` values. This is a subclass of :exc:`OSError`.
347
Georg Brandl116aa622007-08-15 14:28:22 +0000348
349.. exception:: ZeroDivisionError
350
351 Raised when the second argument of a division or modulo operation is zero. The
352 associated value is a string indicating the type of the operands and the
353 operation.
354
355The following exceptions are used as warning categories; see the :mod:`warnings`
356module for more information.
357
358
359.. exception:: Warning
360
361 Base class for warning categories.
362
363
364.. exception:: UserWarning
365
366 Base class for warnings generated by user code.
367
368
369.. exception:: DeprecationWarning
370
371 Base class for warnings about deprecated features.
372
373
374.. exception:: PendingDeprecationWarning
375
376 Base class for warnings about features which will be deprecated in the future.
377
378
379.. exception:: SyntaxWarning
380
381 Base class for warnings about dubious syntax
382
383
384.. exception:: RuntimeWarning
385
386 Base class for warnings about dubious runtime behavior.
387
388
389.. exception:: FutureWarning
390
391 Base class for warnings about constructs that will change semantically in the
392 future.
393
394
395.. exception:: ImportWarning
396
397 Base class for warnings about probable mistakes in module imports.
398
Georg Brandl116aa622007-08-15 14:28:22 +0000399
400.. exception:: UnicodeWarning
401
402 Base class for warnings related to Unicode.
403
Georg Brandl116aa622007-08-15 14:28:22 +0000404The class hierarchy for built-in exceptions is:
405
406
407.. literalinclude:: ../../Lib/test/exception_hierarchy.txt