blob: 786e8253702303e5d49dc53f40dede570fd60f3d [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
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000138 Raise when a :term:`generator`\'s :meth:`close` method is called. It
139 directly inherits from :exc:`BaseException` instead of :exc:`Exception` since
140 it is technically not an error.
Georg Brandl116aa622007-08-15 14:28:22 +0000141
Georg Brandl116aa622007-08-15 14:28:22 +0000142
143.. exception:: IOError
144
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000145 Raised when an I/O operation (such as the built-in :func:`print` or
146 :func:`open` functions or a method of a file object) fails for an I/O-related
Georg Brandl116aa622007-08-15 14:28:22 +0000147 reason, e.g., "file not found" or "disk full".
148
Georg Brandl116aa622007-08-15 14:28:22 +0000149 This class is derived from :exc:`EnvironmentError`. See the discussion above
150 for more information on exception instance attributes.
151
152
153.. exception:: ImportError
154
155 Raised when an :keyword:`import` statement fails to find the module definition
156 or when a ``from ... import`` fails to find a name that is to be imported.
157
Georg Brandl116aa622007-08-15 14:28:22 +0000158
159.. exception:: IndexError
160
161 Raised when a sequence subscript is out of range. (Slice indices are silently
162 truncated to fall in the allowed range; if an index is not a plain integer,
163 :exc:`TypeError` is raised.)
164
165 .. % XXXJH xref to sequences
166
167
168.. exception:: KeyError
169
170 Raised when a mapping (dictionary) key is not found in the set of existing keys.
171
172 .. % XXXJH xref to mapping objects?
173
174
175.. exception:: KeyboardInterrupt
176
177 Raised when the user hits the interrupt key (normally :kbd:`Control-C` or
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000178 :kbd:`Delete`). During execution, a check for interrupts is made
179 regularly. The exception inherits from :exc:`BaseException` so as to not be
180 accidentally caught by code that catches :exc:`Exception` and thus prevent
181 the interpreter from exiting.
Georg Brandl116aa622007-08-15 14:28:22 +0000182
Georg Brandl116aa622007-08-15 14:28:22 +0000183
184.. exception:: MemoryError
185
186 Raised when an operation runs out of memory but the situation may still be
187 rescued (by deleting some objects). The associated value is a string indicating
188 what kind of (internal) operation ran out of memory. Note that because of the
189 underlying memory management architecture (C's :cfunc:`malloc` function), the
190 interpreter may not always be able to completely recover from this situation; it
191 nevertheless raises an exception so that a stack traceback can be printed, in
192 case a run-away program was the cause.
193
194
195.. exception:: NameError
196
197 Raised when a local or global name is not found. This applies only to
198 unqualified names. The associated value is an error message that includes the
199 name that could not be found.
200
201
202.. exception:: NotImplementedError
203
204 This exception is derived from :exc:`RuntimeError`. In user defined base
205 classes, abstract methods should raise this exception when they require derived
206 classes to override the method.
207
Georg Brandl116aa622007-08-15 14:28:22 +0000208
209.. exception:: OSError
210
211 This class is derived from :exc:`EnvironmentError` and is used primarily as the
212 :mod:`os` module's ``os.error`` exception. See :exc:`EnvironmentError` above for
213 a description of the possible associated values.
214
Georg Brandl116aa622007-08-15 14:28:22 +0000215
216.. exception:: OverflowError
217
218 Raised when the result of an arithmetic operation is too large to be
Georg Brandlba956ae2007-11-29 17:24:34 +0000219 represented. This cannot occur for integers (which would rather raise
Georg Brandl116aa622007-08-15 14:28:22 +0000220 :exc:`MemoryError` than give up). Because of the lack of standardization of
221 floating point exception handling in C, most floating point operations also
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000222 aren't checked.
Georg Brandl116aa622007-08-15 14:28:22 +0000223
224
225.. exception:: ReferenceError
226
227 This exception is raised when a weak reference proxy, created by the
228 :func:`weakref.proxy` function, is used to access an attribute of the referent
229 after it has been garbage collected. For more information on weak references,
230 see the :mod:`weakref` module.
231
Georg Brandl116aa622007-08-15 14:28:22 +0000232
233.. exception:: RuntimeError
234
235 Raised when an error is detected that doesn't fall in any of the other
236 categories. The associated value is a string indicating what precisely went
237 wrong. (This exception is mostly a relic from a previous version of the
238 interpreter; it is not used very much any more.)
239
240
241.. exception:: StopIteration
242
Georg Brandl9afde1c2007-11-01 20:32:30 +0000243 Raised by builtin :func:`next` and an :term:`iterator`\'s :meth:`__next__`
244 method to signal that there are no further values.
Georg Brandl116aa622007-08-15 14:28:22 +0000245
Georg Brandl116aa622007-08-15 14:28:22 +0000246
247.. exception:: SyntaxError
248
249 Raised when the parser encounters a syntax error. This may occur in an
250 :keyword:`import` statement, in a call to the built-in functions :func:`exec`
251 or :func:`eval`, or when reading the initial script or standard input
252 (also interactively).
253
Georg Brandl116aa622007-08-15 14:28:22 +0000254 Instances of this class have attributes :attr:`filename`, :attr:`lineno`,
255 :attr:`offset` and :attr:`text` for easier access to the details. :func:`str`
256 of the exception instance returns only the message.
257
258
259.. exception:: SystemError
260
261 Raised when the interpreter finds an internal error, but the situation does not
262 look so serious to cause it to abandon all hope. The associated value is a
263 string indicating what went wrong (in low-level terms).
264
265 You should report this to the author or maintainer of your Python interpreter.
266 Be sure to report the version of the Python interpreter (``sys.version``; it is
267 also printed at the start of an interactive Python session), the exact error
268 message (the exception's associated value) and if possible the source of the
269 program that triggered the error.
270
271
272.. exception:: SystemExit
273
274 This exception is raised by the :func:`sys.exit` function. When it is not
275 handled, the Python interpreter exits; no stack traceback is printed. If the
276 associated value is a plain integer, it specifies the system exit status (passed
277 to C's :cfunc:`exit` function); if it is ``None``, the exit status is zero; if
278 it has another type (such as a string), the object's value is printed and the
279 exit status is one.
280
Georg Brandl116aa622007-08-15 14:28:22 +0000281 Instances have an attribute :attr:`code` which is set to the proposed exit
282 status or error message (defaulting to ``None``). Also, this exception derives
283 directly from :exc:`BaseException` and not :exc:`Exception`, since it is not
284 technically an error.
285
286 A call to :func:`sys.exit` is translated into an exception so that clean-up
287 handlers (:keyword:`finally` clauses of :keyword:`try` statements) can be
288 executed, and so that a debugger can execute a script without running the risk
289 of losing control. The :func:`os._exit` function can be used if it is
290 absolutely positively necessary to exit immediately (for example, in the child
291 process after a call to :func:`fork`).
292
293 The exception inherits from :exc:`BaseException` instead of :exc:`Exception` so
294 that it is not accidentally caught by code that catches :exc:`Exception`. This
295 allows the exception to properly propagate up and cause the interpreter to exit.
296
Georg Brandl116aa622007-08-15 14:28:22 +0000297
298.. exception:: TypeError
299
300 Raised when an operation or function is applied to an object of inappropriate
301 type. The associated value is a string giving details about the type mismatch.
302
303
304.. exception:: UnboundLocalError
305
306 Raised when a reference is made to a local variable in a function or method, but
307 no value has been bound to that variable. This is a subclass of
308 :exc:`NameError`.
309
Georg Brandl116aa622007-08-15 14:28:22 +0000310
311.. exception:: UnicodeError
312
313 Raised when a Unicode-related encoding or decoding error occurs. It is a
314 subclass of :exc:`ValueError`.
315
Georg Brandl116aa622007-08-15 14:28:22 +0000316
317.. exception:: UnicodeEncodeError
318
319 Raised when a Unicode-related error occurs during encoding. It is a subclass of
320 :exc:`UnicodeError`.
321
Georg Brandl116aa622007-08-15 14:28:22 +0000322
323.. exception:: UnicodeDecodeError
324
325 Raised when a Unicode-related error occurs during decoding. It is a subclass of
326 :exc:`UnicodeError`.
327
Georg Brandl116aa622007-08-15 14:28:22 +0000328
329.. exception:: UnicodeTranslateError
330
331 Raised when a Unicode-related error occurs during translating. It is a subclass
332 of :exc:`UnicodeError`.
333
Georg Brandl116aa622007-08-15 14:28:22 +0000334
335.. exception:: ValueError
336
337 Raised when a built-in operation or function receives an argument that has the
338 right type but an inappropriate value, and the situation is not described by a
339 more precise exception such as :exc:`IndexError`.
340
341
342.. exception:: WindowsError
343
344 Raised when a Windows-specific error occurs or when the error number does not
345 correspond to an :cdata:`errno` value. The :attr:`winerror` and
346 :attr:`strerror` values are created from the return values of the
347 :cfunc:`GetLastError` and :cfunc:`FormatMessage` functions from the Windows
348 Platform API. The :attr:`errno` value maps the :attr:`winerror` value to
349 corresponding ``errno.h`` values. This is a subclass of :exc:`OSError`.
350
Georg Brandl116aa622007-08-15 14:28:22 +0000351
352.. exception:: ZeroDivisionError
353
354 Raised when the second argument of a division or modulo operation is zero. The
355 associated value is a string indicating the type of the operands and the
356 operation.
357
358The following exceptions are used as warning categories; see the :mod:`warnings`
359module for more information.
360
361
362.. exception:: Warning
363
364 Base class for warning categories.
365
366
367.. exception:: UserWarning
368
369 Base class for warnings generated by user code.
370
371
372.. exception:: DeprecationWarning
373
374 Base class for warnings about deprecated features.
375
376
377.. exception:: PendingDeprecationWarning
378
379 Base class for warnings about features which will be deprecated in the future.
380
381
382.. exception:: SyntaxWarning
383
384 Base class for warnings about dubious syntax
385
386
387.. exception:: RuntimeWarning
388
389 Base class for warnings about dubious runtime behavior.
390
391
392.. exception:: FutureWarning
393
394 Base class for warnings about constructs that will change semantically in the
395 future.
396
397
398.. exception:: ImportWarning
399
400 Base class for warnings about probable mistakes in module imports.
401
Georg Brandl116aa622007-08-15 14:28:22 +0000402
403.. exception:: UnicodeWarning
404
405 Base class for warnings related to Unicode.
406
Guido van Rossum98297ee2007-11-06 21:34:58 +0000407.. exception:: BytesWarning
Georg Brandl116aa622007-08-15 14:28:22 +0000408
Guido van Rossum98297ee2007-11-06 21:34:58 +0000409 Base class for warnings related to :class:`bytes` and :class:`buffer`.
410
411
412The class hierarchy for built-in exceptions is:
Georg Brandl116aa622007-08-15 14:28:22 +0000413
414.. literalinclude:: ../../Lib/test/exception_hierarchy.txt