blob: 1747efe2ed5eb313d5d5b7c5082dcbac0f3c23a5 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. _bltin-exceptions:
2
3Built-in Exceptions
4===================
5
Georg Brandl116aa622007-08-15 14:28:22 +00006.. index::
7 statement: try
8 statement: except
9
Georg Brandlfbd1b222009-12-29 21:38:35 +000010In Python, all exceptions must be instances of a class that derives from
11:class:`BaseException`. In a :keyword:`try` statement with an :keyword:`except`
Georg Brandl116aa622007-08-15 14:28:22 +000012clause that mentions a particular class, that clause also handles any exception
13classes derived from that class (but not exception classes from which *it* is
14derived). Two exception classes that are not related via subclassing are never
15equivalent, even if they have the same name.
16
17.. index:: statement: raise
18
19The built-in exceptions listed below can be generated by the interpreter or
20built-in functions. Except where mentioned, they have an "associated value"
Georg Brandlfb6fd5d2011-01-07 18:28:45 +000021indicating the detailed cause of the error. This may be a string or a tuple of
22several items of information (e.g., an error code and a string explaining the
23code). The associated value is usually passed as arguments to the exception
24class's constructor.
Georg Brandl116aa622007-08-15 14:28:22 +000025
26User code can raise built-in exceptions. This can be used to test an exception
27handler or to report an error condition "just like" the situation in which the
28interpreter raises the same exception; but beware that there is nothing to
29prevent user code from raising an inappropriate error.
30
Mark Dickinsonabf079d2014-04-14 11:20:12 -040031The built-in exception classes can be subclassed to define new exceptions;
32programmers are encouraged to derive new exceptions from the :exc:`Exception`
33class or one of its subclasses, and not from :exc:`BaseException`. More
34information on defining exceptions is available in the Python Tutorial under
Georg Brandl116aa622007-08-15 14:28:22 +000035:ref:`tut-userexceptions`.
36
Georg Brandle4196d32014-10-31 09:41:46 +010037When raising (or re-raising) an exception in an :keyword:`except` or
38:keyword:`finally` clause
Nick Coghlanab7bf212012-02-26 17:49:52 +100039:attr:`__context__` is automatically set to the last exception caught; if the
40new exception is not handled the traceback that is eventually displayed will
41include the originating exception(s) and the final exception.
42
Nick Coghlan0eee97c2012-12-09 16:21:46 +100043When raising a new exception (rather than using a bare ``raise`` to re-raise
44the exception currently being handled), the implicit exception context can be
45supplemented with an explicit cause by using :keyword:`from` with
46:keyword:`raise`::
47
48 raise new_exc from original_exc
49
50The expression following :keyword:`from` must be an exception or ``None``. It
51will be set as :attr:`__cause__` on the raised exception. Setting
52:attr:`__cause__` also implicitly sets the :attr:`__suppress_context__`
53attribute to ``True``, so that using ``raise new_exc from None``
54effectively replaces the old exception with the new one for display
55purposes (e.g. converting :exc:`KeyError` to :exc:`AttributeError`, while
56leaving the old exception available in :attr:`__context__` for introspection
57when debugging.
Nick Coghlanab7bf212012-02-26 17:49:52 +100058
Nick Coghlan8e18fc82012-12-08 21:39:24 +100059The default traceback display code shows these chained exceptions in
60addition to the traceback for the exception itself. An explicitly chained
61exception in :attr:`__cause__` is always shown when present. An implicitly
62chained exception in :attr:`__context__` is shown only if :attr:`__cause__`
Nick Coghlan0eee97c2012-12-09 16:21:46 +100063is :const:`None` and :attr:`__suppress_context__` is false.
Nick Coghlan8e18fc82012-12-08 21:39:24 +100064
65In either case, the exception itself is always shown after any chained
66exceptions so that the final line of the traceback always shows the last
67exception that was raised.
Nick Coghlanab7bf212012-02-26 17:49:52 +100068
Antoine Pitrouf9c77462011-10-12 16:02:00 +020069
70Base classes
71------------
72
Georg Brandlfbd1b222009-12-29 21:38:35 +000073The following exceptions are used mostly as base classes for other exceptions.
Georg Brandl116aa622007-08-15 14:28:22 +000074
Georg Brandl116aa622007-08-15 14:28:22 +000075.. exception:: BaseException
76
77 The base class for all built-in exceptions. It is not meant to be directly
Georg Brandlfb6fd5d2011-01-07 18:28:45 +000078 inherited by user-defined classes (for that, use :exc:`Exception`). If
Amaury Forgeot d'Arc3b1acf12011-11-22 19:34:08 +010079 :func:`str` is called on an instance of this class, the representation of
80 the argument(s) to the instance are returned, or the empty string when
81 there were no arguments.
Georg Brandlfb6fd5d2011-01-07 18:28:45 +000082
83 .. attribute:: args
84
85 The tuple of arguments given to the exception constructor. Some built-in
Andrew Svetlov5898d4f2014-04-01 00:44:13 +030086 exceptions (like :exc:`OSError`) expect a certain number of arguments and
Georg Brandlfb6fd5d2011-01-07 18:28:45 +000087 assign a special meaning to the elements of this tuple, while others are
88 usually called only with a single string giving an error message.
89
90 .. method:: with_traceback(tb)
91
92 This method sets *tb* as the new traceback for the exception and returns
93 the exception object. It is usually used in exception handling code like
94 this::
95
96 try:
97 ...
98 except SomeException:
99 tb = sys.exc_info()[2]
100 raise OtherException(...).with_traceback(tb)
Georg Brandl116aa622007-08-15 14:28:22 +0000101
Georg Brandl116aa622007-08-15 14:28:22 +0000102
103.. exception:: Exception
104
105 All built-in, non-system-exiting exceptions are derived from this class. All
106 user-defined exceptions should also be derived from this class.
107
Georg Brandl116aa622007-08-15 14:28:22 +0000108
109.. exception:: ArithmeticError
110
111 The base class for those built-in exceptions that are raised for various
112 arithmetic errors: :exc:`OverflowError`, :exc:`ZeroDivisionError`,
113 :exc:`FloatingPointError`.
114
115
Georg Brandl0bdfbfa2010-12-18 17:51:28 +0000116.. exception:: BufferError
117
118 Raised when a :ref:`buffer <bufferobjects>` related operation cannot be
119 performed.
120
121
Georg Brandl116aa622007-08-15 14:28:22 +0000122.. exception:: LookupError
123
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000124 The base class for the exceptions that are raised when a key or index used on
125 a mapping or sequence is invalid: :exc:`IndexError`, :exc:`KeyError`. This
126 can be raised directly by :func:`codecs.lookup`.
Georg Brandl116aa622007-08-15 14:28:22 +0000127
128
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200129Concrete exceptions
130-------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000131
Georg Brandlfbd1b222009-12-29 21:38:35 +0000132The following exceptions are the exceptions that are usually raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000133
134.. exception:: AssertionError
135
136 .. index:: statement: assert
137
138 Raised when an :keyword:`assert` statement fails.
139
140
141.. exception:: AttributeError
142
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000143 Raised when an attribute reference (see :ref:`attribute-references`) or
144 assignment fails. (When an object does not support attribute references or
145 attribute assignments at all, :exc:`TypeError` is raised.)
Georg Brandl116aa622007-08-15 14:28:22 +0000146
147
148.. exception:: EOFError
149
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300150 Raised when the :func:`input` function hits an end-of-file condition (EOF)
151 without reading any data. (N.B.: the :meth:`io.IOBase.read` and
152 :meth:`io.IOBase.readline` methods return an empty string when they hit EOF.)
Georg Brandl116aa622007-08-15 14:28:22 +0000153
154
155.. exception:: FloatingPointError
156
157 Raised when a floating point operation fails. This exception is always defined,
158 but can only be raised when Python is configured with the
Éric Araujo713d3032010-11-18 16:38:46 +0000159 ``--with-fpectl`` option, or the :const:`WANT_SIGFPE_HANDLER` symbol is
Georg Brandl116aa622007-08-15 14:28:22 +0000160 defined in the :file:`pyconfig.h` file.
161
162
163.. exception:: GeneratorExit
164
Yury Selivanov66f88282015-06-24 11:04:15 -0400165 Raised when a :term:`generator` or :term:`coroutine` is closed;
166 see :meth:`generator.close` and :meth:`coroutine.close`. It
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000167 directly inherits from :exc:`BaseException` instead of :exc:`Exception` since
168 it is technically not an error.
Georg Brandl116aa622007-08-15 14:28:22 +0000169
Georg Brandl116aa622007-08-15 14:28:22 +0000170
Georg Brandl116aa622007-08-15 14:28:22 +0000171.. exception:: ImportError
172
Brett Cannon679ecb52013-07-04 17:51:50 -0400173 Raised when an :keyword:`import` statement fails to find the module definition
174 or when a ``from ... import`` fails to find a name that is to be imported.
Georg Brandl116aa622007-08-15 14:28:22 +0000175
Brett Cannon79ec55e2012-04-12 20:24:54 -0400176 The :attr:`name` and :attr:`path` attributes can be set using keyword-only
177 arguments to the constructor. When set they represent the name of the module
178 that was attempted to be imported and the path to any file which triggered
179 the exception, respectively.
180
181 .. versionchanged:: 3.3
182 Added the :attr:`name` and :attr:`path` attributes.
183
Georg Brandl116aa622007-08-15 14:28:22 +0000184
185.. exception:: IndexError
186
Georg Brandl95817b32008-05-11 14:30:18 +0000187 Raised when a sequence subscript is out of range. (Slice indices are
188 silently truncated to fall in the allowed range; if an index is not an
189 integer, :exc:`TypeError` is raised.)
Georg Brandl116aa622007-08-15 14:28:22 +0000190
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000191 .. XXX xref to sequences
Georg Brandl116aa622007-08-15 14:28:22 +0000192
193
194.. exception:: KeyError
195
196 Raised when a mapping (dictionary) key is not found in the set of existing keys.
197
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000198 .. XXX xref to mapping objects?
Georg Brandl116aa622007-08-15 14:28:22 +0000199
200
201.. exception:: KeyboardInterrupt
202
203 Raised when the user hits the interrupt key (normally :kbd:`Control-C` or
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000204 :kbd:`Delete`). During execution, a check for interrupts is made
205 regularly. The exception inherits from :exc:`BaseException` so as to not be
206 accidentally caught by code that catches :exc:`Exception` and thus prevent
207 the interpreter from exiting.
Georg Brandl116aa622007-08-15 14:28:22 +0000208
Georg Brandl116aa622007-08-15 14:28:22 +0000209
210.. exception:: MemoryError
211
212 Raised when an operation runs out of memory but the situation may still be
213 rescued (by deleting some objects). The associated value is a string indicating
214 what kind of (internal) operation ran out of memory. Note that because of the
Georg Brandl60203b42010-10-06 10:11:56 +0000215 underlying memory management architecture (C's :c:func:`malloc` function), the
Georg Brandl116aa622007-08-15 14:28:22 +0000216 interpreter may not always be able to completely recover from this situation; it
217 nevertheless raises an exception so that a stack traceback can be printed, in
218 case a run-away program was the cause.
219
220
221.. exception:: NameError
222
223 Raised when a local or global name is not found. This applies only to
224 unqualified names. The associated value is an error message that includes the
225 name that could not be found.
226
227
228.. exception:: NotImplementedError
229
230 This exception is derived from :exc:`RuntimeError`. In user defined base
Ethan Furman20bd9f02016-08-05 15:10:16 -0700231 classes, abstract methods should raise this exception when they require
232 derived classes to override the method, or while the class is being
233 developed to indicate that the real implementation still needs to be added.
Georg Brandl116aa622007-08-15 14:28:22 +0000234
Ethan Furman20bd9f02016-08-05 15:10:16 -0700235 .. note::
236
237 It should not be used to indicate that an operater or method is not
238 meant to be supported at all -- in that case either leave the operator /
239 method undefined or, if a subclass, set it to :data:`None`.
240
241 .. note::
242
243 ``NotImplementedError`` and ``NotImplemented`` are not interchangeable,
244 even though they have similar names and purposes. See
245 :data:`NotImplemented` for details on when to use it.
Georg Brandl116aa622007-08-15 14:28:22 +0000246
Martin Panter5487c132015-10-26 11:05:42 +0000247.. exception:: OSError([arg])
248 OSError(errno, strerror[, filename[, winerror[, filename2]]])
Georg Brandl116aa622007-08-15 14:28:22 +0000249
Christian Heimesa62da1d2008-01-12 19:39:10 +0000250 .. index:: module: errno
251
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200252 This exception is raised when a system function returns a system-related
253 error, including I/O failures such as "file not found" or "disk full"
Martin Panter5487c132015-10-26 11:05:42 +0000254 (not for illegal argument types or other incidental errors).
Christian Heimesa62da1d2008-01-12 19:39:10 +0000255
Martin Panter5487c132015-10-26 11:05:42 +0000256 The second form of the constructor sets the corresponding attributes,
257 described below. The attributes default to :const:`None` if not
258 specified. For backwards compatibility, if three arguments are passed,
259 the :attr:`~BaseException.args` attribute contains only a 2-tuple
260 of the first two constructor arguments.
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200261
Martin Panter5487c132015-10-26 11:05:42 +0000262 The constructor often actually returns a subclass of :exc:`OSError`, as
263 described in `OS exceptions`_ below. The particular subclass depends on
264 the final :attr:`.errno` value. This behaviour only occurs when
265 constructing :exc:`OSError` directly or via an alias, and is not
266 inherited when subclassing.
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200267
Martin Panter5487c132015-10-26 11:05:42 +0000268 .. attribute:: errno
269
270 A numeric error code from the C variable :c:data:`errno`.
271
272 .. attribute:: winerror
273
274 Under Windows, this gives you the native
275 Windows error code. The :attr:`.errno` attribute is then an approximate
276 translation, in POSIX terms, of that native error code.
277
278 Under Windows, if the *winerror* constructor argument is an integer,
279 the :attr:`.errno` attribute is determined from the Windows error code,
280 and the *errno* argument is ignored. On other platforms, the
281 *winerror* argument is ignored, and the :attr:`winerror` attribute
282 does not exist.
283
284 .. attribute:: strerror
285
286 The corresponding error message, as provided by
287 the operating system. It is formatted by the C
288 functions :c:func:`perror` under POSIX, and :c:func:`FormatMessage`
289 under Windows.
290
291 .. attribute:: filename
292 filename2
293
294 For exceptions that involve a file system path (such as :func:`open` or
295 :func:`os.unlink`), :attr:`filename` is the file name passed to the function.
296 For functions that involve two file system paths (such as
297 :func:`os.rename`), :attr:`filename2` corresponds to the second
298 file name passed to the function.
Larry Hastingsb0827312014-02-09 22:05:19 -0800299
Georg Brandl116aa622007-08-15 14:28:22 +0000300
Antoine Pitrou195e7022011-10-12 16:46:46 +0200301 .. versionchanged:: 3.3
302 :exc:`EnvironmentError`, :exc:`IOError`, :exc:`WindowsError`,
Berker Peksag8fafc742016-04-11 12:23:04 +0300303 :exc:`socket.error`, :exc:`select.error` and
Martin Panter5487c132015-10-26 11:05:42 +0000304 :exc:`mmap.error` have been merged into :exc:`OSError`, and the
305 constructor may return a subclass.
Antoine Pitrou195e7022011-10-12 16:46:46 +0200306
Victor Stinner292c8352012-10-30 02:17:38 +0100307 .. versionchanged:: 3.4
Victor Stinner292c8352012-10-30 02:17:38 +0100308 The :attr:`filename` attribute is now the original file name passed to
309 the function, instead of the name encoded to or decoded from the
Martin Panter5487c132015-10-26 11:05:42 +0000310 filesystem encoding. Also, the *filename2* constructor argument and
311 attribute was added.
Victor Stinner292c8352012-10-30 02:17:38 +0100312
Georg Brandl116aa622007-08-15 14:28:22 +0000313
314.. exception:: OverflowError
315
316 Raised when the result of an arithmetic operation is too large to be
Georg Brandlba956ae2007-11-29 17:24:34 +0000317 represented. This cannot occur for integers (which would rather raise
Terry Jan Reedyb6d1f482014-06-16 03:31:00 -0400318 :exc:`MemoryError` than give up). However, for historical reasons,
319 OverflowError is sometimes raised for integers that are outside a required
320 range. Because of the lack of standardization of floating point exception
321 handling in C, most floating point operations are not checked.
Georg Brandl116aa622007-08-15 14:28:22 +0000322
323
Yury Selivanovf488fb42015-07-03 01:04:23 -0400324.. exception:: RecursionError
325
326 This exception is derived from :exc:`RuntimeError`. It is raised when the
327 interpreter detects that the maximum recursion depth (see
328 :func:`sys.getrecursionlimit`) is exceeded.
329
330 .. versionadded:: 3.5
331 Previously, a plain :exc:`RuntimeError` was raised.
332
333
Georg Brandl116aa622007-08-15 14:28:22 +0000334.. exception:: ReferenceError
335
336 This exception is raised when a weak reference proxy, created by the
337 :func:`weakref.proxy` function, is used to access an attribute of the referent
338 after it has been garbage collected. For more information on weak references,
339 see the :mod:`weakref` module.
340
Georg Brandl116aa622007-08-15 14:28:22 +0000341
342.. exception:: RuntimeError
343
344 Raised when an error is detected that doesn't fall in any of the other
345 categories. The associated value is a string indicating what precisely went
Antoine Pitrou9527f162013-11-25 19:08:32 +0100346 wrong.
Georg Brandl116aa622007-08-15 14:28:22 +0000347
348
349.. exception:: StopIteration
350
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000351 Raised by built-in function :func:`next` and an :term:`iterator`\'s
Ezio Melotti1dd7c302012-10-12 13:45:38 +0300352 :meth:`~iterator.__next__` method to signal that there are no further
353 items produced by the iterator.
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000354
355 The exception object has a single attribute :attr:`value`, which is
356 given as an argument when constructing the exception, and defaults
357 to :const:`None`.
358
Yury Selivanov66f88282015-06-24 11:04:15 -0400359 When a :term:`generator` or :term:`coroutine` function
360 returns, a new :exc:`StopIteration` instance is
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000361 raised, and the value returned by the function is used as the
362 :attr:`value` parameter to the constructor of the exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000363
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400364 If a generator function defined in the presence of a ``from __future__
365 import generator_stop`` directive raises :exc:`StopIteration`, it will be
366 converted into a :exc:`RuntimeError` (retaining the :exc:`StopIteration`
367 as the new exception's cause).
368
Nick Coghlan0ed80192012-01-14 14:43:24 +1000369 .. versionchanged:: 3.3
370 Added ``value`` attribute and the ability for generator functions to
371 use it to return a value.
Georg Brandl116aa622007-08-15 14:28:22 +0000372
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400373 .. versionchanged:: 3.5
374 Introduced the RuntimeError transformation.
375
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400376.. exception:: StopAsyncIteration
377
378 Must be raised by :meth:`__anext__` method of an
379 :term:`asynchronous iterator` object to stop the iteration.
380
381 .. versionadded:: 3.5
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400382
Georg Brandl116aa622007-08-15 14:28:22 +0000383.. exception:: SyntaxError
384
385 Raised when the parser encounters a syntax error. This may occur in an
386 :keyword:`import` statement, in a call to the built-in functions :func:`exec`
387 or :func:`eval`, or when reading the initial script or standard input
388 (also interactively).
389
Georg Brandl116aa622007-08-15 14:28:22 +0000390 Instances of this class have attributes :attr:`filename`, :attr:`lineno`,
391 :attr:`offset` and :attr:`text` for easier access to the details. :func:`str`
392 of the exception instance returns only the message.
393
394
Georg Brandl0bdfbfa2010-12-18 17:51:28 +0000395.. exception:: IndentationError
396
397 Base class for syntax errors related to incorrect indentation. This is a
398 subclass of :exc:`SyntaxError`.
399
400
401.. exception:: TabError
402
403 Raised when indentation contains an inconsistent use of tabs and spaces.
404 This is a subclass of :exc:`IndentationError`.
405
406
Georg Brandl116aa622007-08-15 14:28:22 +0000407.. exception:: SystemError
408
409 Raised when the interpreter finds an internal error, but the situation does not
410 look so serious to cause it to abandon all hope. The associated value is a
411 string indicating what went wrong (in low-level terms).
412
413 You should report this to the author or maintainer of your Python interpreter.
414 Be sure to report the version of the Python interpreter (``sys.version``; it is
415 also printed at the start of an interactive Python session), the exact error
416 message (the exception's associated value) and if possible the source of the
417 program that triggered the error.
418
419
420.. exception:: SystemExit
421
Berker Peksag77a6b202015-03-10 14:47:15 +0200422 This exception is raised by the :func:`sys.exit` function. It inherits from
423 :exc:`BaseException` instead of :exc:`Exception` so that it is not accidentally
424 caught by code that catches :exc:`Exception`. This allows the exception to
425 properly propagate up and cause the interpreter to exit. When it is not
426 handled, the Python interpreter exits; no stack traceback is printed. The
427 constructor accepts the same optional argument passed to :func:`sys.exit`.
428 If the value is an integer, it specifies the system exit status (passed to
429 C's :c:func:`exit` function); if it is ``None``, the exit status is zero; if
430 it has another type (such as a string), the object's value is printed and
Georg Brandl95817b32008-05-11 14:30:18 +0000431 the exit status is one.
Georg Brandl116aa622007-08-15 14:28:22 +0000432
Georg Brandl116aa622007-08-15 14:28:22 +0000433 A call to :func:`sys.exit` is translated into an exception so that clean-up
434 handlers (:keyword:`finally` clauses of :keyword:`try` statements) can be
435 executed, and so that a debugger can execute a script without running the risk
436 of losing control. The :func:`os._exit` function can be used if it is
437 absolutely positively necessary to exit immediately (for example, in the child
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300438 process after a call to :func:`os.fork`).
Georg Brandl116aa622007-08-15 14:28:22 +0000439
Berker Peksag77a6b202015-03-10 14:47:15 +0200440 .. attribute:: code
441
442 The exit status or error message that is passed to the constructor.
443 (Defaults to ``None``.)
Georg Brandl116aa622007-08-15 14:28:22 +0000444
Georg Brandl116aa622007-08-15 14:28:22 +0000445
446.. exception:: TypeError
447
448 Raised when an operation or function is applied to an object of inappropriate
449 type. The associated value is a string giving details about the type mismatch.
450
Ethan Furman20bd9f02016-08-05 15:10:16 -0700451 This exception may be raised by user code to indicate that an attempted
452 operation on an object is not supported, and is not meant to be. If an object
453 is meant to support a given operation but has not yet provided an
454 implementation, :exc:`NotImplementedError` is the proper exception to raise.
455
456 Passing arguments of the wrong type (e.g. passing a :class:`list` when an
457 :class:`int` is expected) should result in a :exc:`TypeError`, but passing
458 arguments with the wrong value (e.g. a number outside expected boundaries)
459 should result in a :exc:`ValueError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000460
461.. exception:: UnboundLocalError
462
463 Raised when a reference is made to a local variable in a function or method, but
464 no value has been bound to that variable. This is a subclass of
465 :exc:`NameError`.
466
Georg Brandl116aa622007-08-15 14:28:22 +0000467
468.. exception:: UnicodeError
469
470 Raised when a Unicode-related encoding or decoding error occurs. It is a
471 subclass of :exc:`ValueError`.
472
Benjamin Peterson78f7e3a2012-12-02 11:33:06 -0500473 :exc:`UnicodeError` has attributes that describe the encoding or decoding
474 error. For example, ``err.object[err.start:err.end]`` gives the particular
475 invalid input that the codec failed on.
476
477 .. attribute:: encoding
478
479 The name of the encoding that raised the error.
480
481 .. attribute:: reason
482
483 A string describing the specific codec error.
484
485 .. attribute:: object
486
487 The object the codec was attempting to encode or decode.
488
489 .. attribute:: start
490
491 The first index of invalid data in :attr:`object`.
492
493 .. attribute:: end
494
495 The index after the last invalid data in :attr:`object`.
496
Georg Brandl116aa622007-08-15 14:28:22 +0000497
498.. exception:: UnicodeEncodeError
499
500 Raised when a Unicode-related error occurs during encoding. It is a subclass of
501 :exc:`UnicodeError`.
502
Georg Brandl116aa622007-08-15 14:28:22 +0000503
504.. exception:: UnicodeDecodeError
505
506 Raised when a Unicode-related error occurs during decoding. It is a subclass of
507 :exc:`UnicodeError`.
508
Georg Brandl116aa622007-08-15 14:28:22 +0000509
510.. exception:: UnicodeTranslateError
511
512 Raised when a Unicode-related error occurs during translating. It is a subclass
513 of :exc:`UnicodeError`.
514
Georg Brandl116aa622007-08-15 14:28:22 +0000515
516.. exception:: ValueError
517
518 Raised when a built-in operation or function receives an argument that has the
519 right type but an inappropriate value, and the situation is not described by a
520 more precise exception such as :exc:`IndexError`.
521
522
Georg Brandl116aa622007-08-15 14:28:22 +0000523.. exception:: ZeroDivisionError
524
525 Raised when the second argument of a division or modulo operation is zero. The
526 associated value is a string indicating the type of the operands and the
527 operation.
528
Georg Brandlfbd1b222009-12-29 21:38:35 +0000529
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200530The following exceptions are kept for compatibility with previous versions;
531starting from Python 3.3, they are aliases of :exc:`OSError`.
532
533.. exception:: EnvironmentError
534
535.. exception:: IOError
536
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200537.. exception:: WindowsError
538
539 Only available on Windows.
540
541
542OS exceptions
543^^^^^^^^^^^^^
544
545The following exceptions are subclasses of :exc:`OSError`, they get raised
546depending on the system error code.
547
548.. exception:: BlockingIOError
549
550 Raised when an operation would block on an object (e.g. socket) set
551 for non-blocking operation.
552 Corresponds to :c:data:`errno` ``EAGAIN``, ``EALREADY``,
553 ``EWOULDBLOCK`` and ``EINPROGRESS``.
554
Antoine Pitrouf55011f2011-10-12 18:57:23 +0200555 In addition to those of :exc:`OSError`, :exc:`BlockingIOError` can have
556 one more attribute:
557
558 .. attribute:: characters_written
559
560 An integer containing the number of characters written to the stream
561 before it blocked. This attribute is available when using the
562 buffered I/O classes from the :mod:`io` module.
563
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200564.. exception:: ChildProcessError
565
566 Raised when an operation on a child process failed.
567 Corresponds to :c:data:`errno` ``ECHILD``.
568
569.. exception:: ConnectionError
570
Ezio Melottib24d3cf2012-10-21 03:22:05 +0300571 A base class for connection-related issues.
572
573 Subclasses are :exc:`BrokenPipeError`, :exc:`ConnectionAbortedError`,
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200574 :exc:`ConnectionRefusedError` and :exc:`ConnectionResetError`.
575
Ezio Melottib24d3cf2012-10-21 03:22:05 +0300576.. exception:: BrokenPipeError
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200577
Ezio Melottib24d3cf2012-10-21 03:22:05 +0300578 A subclass of :exc:`ConnectionError`, raised when trying to write on a
579 pipe while the other end has been closed, or trying to write on a socket
580 which has been shutdown for writing.
581 Corresponds to :c:data:`errno` ``EPIPE`` and ``ESHUTDOWN``.
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200582
Ezio Melottib24d3cf2012-10-21 03:22:05 +0300583.. exception:: ConnectionAbortedError
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200584
Ezio Melottib24d3cf2012-10-21 03:22:05 +0300585 A subclass of :exc:`ConnectionError`, raised when a connection attempt
586 is aborted by the peer.
587 Corresponds to :c:data:`errno` ``ECONNABORTED``.
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200588
Ezio Melottib24d3cf2012-10-21 03:22:05 +0300589.. exception:: ConnectionRefusedError
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200590
Ezio Melottib24d3cf2012-10-21 03:22:05 +0300591 A subclass of :exc:`ConnectionError`, raised when a connection attempt
592 is refused by the peer.
593 Corresponds to :c:data:`errno` ``ECONNREFUSED``.
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200594
Ezio Melottib24d3cf2012-10-21 03:22:05 +0300595.. exception:: ConnectionResetError
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200596
Ezio Melottib24d3cf2012-10-21 03:22:05 +0300597 A subclass of :exc:`ConnectionError`, raised when a connection is
598 reset by the peer.
599 Corresponds to :c:data:`errno` ``ECONNRESET``.
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200600
601.. exception:: FileExistsError
602
603 Raised when trying to create a file or directory which already exists.
604 Corresponds to :c:data:`errno` ``EEXIST``.
605
606.. exception:: FileNotFoundError
607
608 Raised when a file or directory is requested but doesn't exist.
609 Corresponds to :c:data:`errno` ``ENOENT``.
610
611.. exception:: InterruptedError
612
613 Raised when a system call is interrupted by an incoming signal.
Victor Stinnerf70e1ca2015-03-30 21:16:11 +0200614 Corresponds to :c:data:`errno` :py:data:`~errno.EINTR`.
615
616 .. versionchanged:: 3.5
617 Python now retries system calls when a syscall is interrupted by a
618 signal, except if the signal handler raises an exception (see :pep:`475`
619 for the rationale), instead of raising :exc:`InterruptedError`.
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200620
621.. exception:: IsADirectoryError
622
623 Raised when a file operation (such as :func:`os.remove`) is requested
624 on a directory.
625 Corresponds to :c:data:`errno` ``EISDIR``.
626
627.. exception:: NotADirectoryError
628
629 Raised when a directory operation (such as :func:`os.listdir`) is requested
630 on something which is not a directory.
631 Corresponds to :c:data:`errno` ``ENOTDIR``.
632
633.. exception:: PermissionError
634
635 Raised when trying to run an operation without the adequate access
636 rights - for example filesystem permissions.
637 Corresponds to :c:data:`errno` ``EACCES`` and ``EPERM``.
638
639.. exception:: ProcessLookupError
640
641 Raised when a given process doesn't exist.
642 Corresponds to :c:data:`errno` ``ESRCH``.
643
644.. exception:: TimeoutError
645
646 Raised when a system function timed out at the system level.
647 Corresponds to :c:data:`errno` ``ETIMEDOUT``.
648
649.. versionadded:: 3.3
650 All the above :exc:`OSError` subclasses were added.
651
652
653.. seealso::
654
655 :pep:`3151` - Reworking the OS and IO exception hierarchy
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200656
657
658Warnings
659--------
660
Georg Brandl116aa622007-08-15 14:28:22 +0000661The following exceptions are used as warning categories; see the :mod:`warnings`
662module for more information.
663
Georg Brandl116aa622007-08-15 14:28:22 +0000664.. exception:: Warning
665
666 Base class for warning categories.
667
668
669.. exception:: UserWarning
670
671 Base class for warnings generated by user code.
672
673
674.. exception:: DeprecationWarning
675
676 Base class for warnings about deprecated features.
677
678
679.. exception:: PendingDeprecationWarning
680
681 Base class for warnings about features which will be deprecated in the future.
682
683
684.. exception:: SyntaxWarning
685
Martin Panterd21e0b52015-10-10 10:36:22 +0000686 Base class for warnings about dubious syntax.
Georg Brandl116aa622007-08-15 14:28:22 +0000687
688
689.. exception:: RuntimeWarning
690
691 Base class for warnings about dubious runtime behavior.
692
693
694.. exception:: FutureWarning
695
696 Base class for warnings about constructs that will change semantically in the
697 future.
698
699
700.. exception:: ImportWarning
701
702 Base class for warnings about probable mistakes in module imports.
703
Georg Brandl116aa622007-08-15 14:28:22 +0000704
705.. exception:: UnicodeWarning
706
707 Base class for warnings related to Unicode.
708
Georg Brandl08be72d2010-10-24 15:11:22 +0000709
Guido van Rossum98297ee2007-11-06 21:34:58 +0000710.. exception:: BytesWarning
Georg Brandl116aa622007-08-15 14:28:22 +0000711
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300712 Base class for warnings related to :class:`bytes` and :class:`bytearray`.
Guido van Rossum98297ee2007-11-06 21:34:58 +0000713
Georg Brandl08be72d2010-10-24 15:11:22 +0000714
715.. exception:: ResourceWarning
716
717 Base class for warnings related to resource usage.
718
719 .. versionadded:: 3.2
720
721
722
Alexandre Vassalottic22c6f22009-07-21 00:51:58 +0000723Exception hierarchy
724-------------------
Guido van Rossum98297ee2007-11-06 21:34:58 +0000725
726The class hierarchy for built-in exceptions is:
Georg Brandl116aa622007-08-15 14:28:22 +0000727
728.. literalinclude:: ../../Lib/test/exception_hierarchy.txt