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