blob: 8fdd6ebecfa69e3696d3dbdb3dddf907218cc5e7 [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
Andre Delfino55f41e42018-12-05 16:45:30 -030055purposes (e.g. converting :exc:`KeyError` to :exc:`AttributeError`), while
Nick Coghlan0eee97c2012-12-09 16:21:46 +100056leaving 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
Irit Katrielc590c232020-12-16 16:03:32 +000093 the exception object. It was more commonly used before the exception
94 chaining features of :pep:`3134` became available. The following example
95 shows how we can convert an instance of ``SomeException`` into an
96 instance of ``OtherException`` while preserving the traceback. Once
97 raised, the current frame is pushed onto the traceback of the
98 ``OtherException``, as would have happened to the traceback of the
99 original ``SomeException`` had we allowed it to propagate to the caller.
Georg Brandlfb6fd5d2011-01-07 18:28:45 +0000100
101 try:
102 ...
103 except SomeException:
104 tb = sys.exc_info()[2]
105 raise OtherException(...).with_traceback(tb)
Georg Brandl116aa622007-08-15 14:28:22 +0000106
Georg Brandl116aa622007-08-15 14:28:22 +0000107
108.. exception:: Exception
109
110 All built-in, non-system-exiting exceptions are derived from this class. All
111 user-defined exceptions should also be derived from this class.
112
Georg Brandl116aa622007-08-15 14:28:22 +0000113
114.. exception:: ArithmeticError
115
116 The base class for those built-in exceptions that are raised for various
117 arithmetic errors: :exc:`OverflowError`, :exc:`ZeroDivisionError`,
118 :exc:`FloatingPointError`.
119
120
Georg Brandl0bdfbfa2010-12-18 17:51:28 +0000121.. exception:: BufferError
122
123 Raised when a :ref:`buffer <bufferobjects>` related operation cannot be
124 performed.
125
126
Georg Brandl116aa622007-08-15 14:28:22 +0000127.. exception:: LookupError
128
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000129 The base class for the exceptions that are raised when a key or index used on
130 a mapping or sequence is invalid: :exc:`IndexError`, :exc:`KeyError`. This
131 can be raised directly by :func:`codecs.lookup`.
Georg Brandl116aa622007-08-15 14:28:22 +0000132
133
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200134Concrete exceptions
135-------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000136
Georg Brandlfbd1b222009-12-29 21:38:35 +0000137The following exceptions are the exceptions that are usually raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000138
139.. exception:: AssertionError
140
141 .. index:: statement: assert
142
143 Raised when an :keyword:`assert` statement fails.
144
145
146.. exception:: AttributeError
147
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000148 Raised when an attribute reference (see :ref:`attribute-references`) or
149 assignment fails. (When an object does not support attribute references or
150 attribute assignments at all, :exc:`TypeError` is raised.)
Georg Brandl116aa622007-08-15 14:28:22 +0000151
Pablo Galindo37494b42021-04-14 02:36:07 +0100152 The :attr:`name` and :attr:`obj` attributes can be set using keyword-only
153 arguments to the constructor. When set they represent the name of the attribute
154 that was attempted to be accessed and the object that was accessed for said
155 attribute, respectively.
156
157 .. versionchanged:: 3.10
158 Added the :attr:`name` and :attr:`obj` attributes.
Georg Brandl116aa622007-08-15 14:28:22 +0000159
160.. exception:: EOFError
161
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300162 Raised when the :func:`input` function hits an end-of-file condition (EOF)
163 without reading any data. (N.B.: the :meth:`io.IOBase.read` and
164 :meth:`io.IOBase.readline` methods return an empty string when they hit EOF.)
Georg Brandl116aa622007-08-15 14:28:22 +0000165
166
167.. exception:: FloatingPointError
168
Nathaniel J. Smith735ae8d2018-01-05 23:15:34 -0800169 Not currently used.
Georg Brandl116aa622007-08-15 14:28:22 +0000170
171
172.. exception:: GeneratorExit
173
Yury Selivanov66f88282015-06-24 11:04:15 -0400174 Raised when a :term:`generator` or :term:`coroutine` is closed;
175 see :meth:`generator.close` and :meth:`coroutine.close`. It
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000176 directly inherits from :exc:`BaseException` instead of :exc:`Exception` since
177 it is technically not an error.
Georg Brandl116aa622007-08-15 14:28:22 +0000178
Georg Brandl116aa622007-08-15 14:28:22 +0000179
Georg Brandl116aa622007-08-15 14:28:22 +0000180.. exception:: ImportError
181
Eric Snowc9432652016-09-07 15:42:32 -0700182 Raised when the :keyword:`import` statement has troubles trying to
183 load a module. Also raised when the "from list" in ``from ... import``
184 has a name that cannot be found.
Georg Brandl116aa622007-08-15 14:28:22 +0000185
Brett Cannon79ec55e2012-04-12 20:24:54 -0400186 The :attr:`name` and :attr:`path` attributes can be set using keyword-only
187 arguments to the constructor. When set they represent the name of the module
188 that was attempted to be imported and the path to any file which triggered
189 the exception, respectively.
190
191 .. versionchanged:: 3.3
192 Added the :attr:`name` and :attr:`path` attributes.
193
Eric Snowc9432652016-09-07 15:42:32 -0700194.. exception:: ModuleNotFoundError
195
196 A subclass of :exc:`ImportError` which is raised by :keyword:`import`
197 when a module could not be located. It is also raised when ``None``
198 is found in :data:`sys.modules`.
199
200 .. versionadded:: 3.6
201
Georg Brandl116aa622007-08-15 14:28:22 +0000202
203.. exception:: IndexError
204
Georg Brandl95817b32008-05-11 14:30:18 +0000205 Raised when a sequence subscript is out of range. (Slice indices are
206 silently truncated to fall in the allowed range; if an index is not an
207 integer, :exc:`TypeError` is raised.)
Georg Brandl116aa622007-08-15 14:28:22 +0000208
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000209 .. XXX xref to sequences
Georg Brandl116aa622007-08-15 14:28:22 +0000210
211
212.. exception:: KeyError
213
214 Raised when a mapping (dictionary) key is not found in the set of existing keys.
215
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000216 .. XXX xref to mapping objects?
Georg Brandl116aa622007-08-15 14:28:22 +0000217
218
219.. exception:: KeyboardInterrupt
220
221 Raised when the user hits the interrupt key (normally :kbd:`Control-C` or
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000222 :kbd:`Delete`). During execution, a check for interrupts is made
223 regularly. The exception inherits from :exc:`BaseException` so as to not be
224 accidentally caught by code that catches :exc:`Exception` and thus prevent
225 the interpreter from exiting.
Georg Brandl116aa622007-08-15 14:28:22 +0000226
Georg Brandl116aa622007-08-15 14:28:22 +0000227
228.. exception:: MemoryError
229
230 Raised when an operation runs out of memory but the situation may still be
231 rescued (by deleting some objects). The associated value is a string indicating
232 what kind of (internal) operation ran out of memory. Note that because of the
Georg Brandl60203b42010-10-06 10:11:56 +0000233 underlying memory management architecture (C's :c:func:`malloc` function), the
Georg Brandl116aa622007-08-15 14:28:22 +0000234 interpreter may not always be able to completely recover from this situation; it
235 nevertheless raises an exception so that a stack traceback can be printed, in
236 case a run-away program was the cause.
237
238
239.. exception:: NameError
240
241 Raised when a local or global name is not found. This applies only to
242 unqualified names. The associated value is an error message that includes the
243 name that could not be found.
244
245
246.. exception:: NotImplementedError
247
248 This exception is derived from :exc:`RuntimeError`. In user defined base
Ethan Furman20bd9f02016-08-05 15:10:16 -0700249 classes, abstract methods should raise this exception when they require
250 derived classes to override the method, or while the class is being
251 developed to indicate that the real implementation still needs to be added.
Georg Brandl116aa622007-08-15 14:28:22 +0000252
Ethan Furman20bd9f02016-08-05 15:10:16 -0700253 .. note::
254
delirious-lettuce3378b202017-05-19 14:37:57 -0600255 It should not be used to indicate that an operator or method is not
Ethan Furman20bd9f02016-08-05 15:10:16 -0700256 meant to be supported at all -- in that case either leave the operator /
257 method undefined or, if a subclass, set it to :data:`None`.
258
259 .. note::
260
261 ``NotImplementedError`` and ``NotImplemented`` are not interchangeable,
262 even though they have similar names and purposes. See
263 :data:`NotImplemented` for details on when to use it.
Georg Brandl116aa622007-08-15 14:28:22 +0000264
Martin Panter5487c132015-10-26 11:05:42 +0000265.. exception:: OSError([arg])
266 OSError(errno, strerror[, filename[, winerror[, filename2]]])
Georg Brandl116aa622007-08-15 14:28:22 +0000267
Christian Heimesa62da1d2008-01-12 19:39:10 +0000268 .. index:: module: errno
269
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200270 This exception is raised when a system function returns a system-related
271 error, including I/O failures such as "file not found" or "disk full"
Martin Panter5487c132015-10-26 11:05:42 +0000272 (not for illegal argument types or other incidental errors).
Christian Heimesa62da1d2008-01-12 19:39:10 +0000273
Martin Panter5487c132015-10-26 11:05:42 +0000274 The second form of the constructor sets the corresponding attributes,
275 described below. The attributes default to :const:`None` if not
276 specified. For backwards compatibility, if three arguments are passed,
277 the :attr:`~BaseException.args` attribute contains only a 2-tuple
278 of the first two constructor arguments.
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200279
Martin Panter5487c132015-10-26 11:05:42 +0000280 The constructor often actually returns a subclass of :exc:`OSError`, as
281 described in `OS exceptions`_ below. The particular subclass depends on
282 the final :attr:`.errno` value. This behaviour only occurs when
283 constructing :exc:`OSError` directly or via an alias, and is not
284 inherited when subclassing.
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200285
Martin Panter5487c132015-10-26 11:05:42 +0000286 .. attribute:: errno
287
288 A numeric error code from the C variable :c:data:`errno`.
289
290 .. attribute:: winerror
291
292 Under Windows, this gives you the native
293 Windows error code. The :attr:`.errno` attribute is then an approximate
294 translation, in POSIX terms, of that native error code.
295
296 Under Windows, if the *winerror* constructor argument is an integer,
297 the :attr:`.errno` attribute is determined from the Windows error code,
298 and the *errno* argument is ignored. On other platforms, the
299 *winerror* argument is ignored, and the :attr:`winerror` attribute
300 does not exist.
301
302 .. attribute:: strerror
303
304 The corresponding error message, as provided by
305 the operating system. It is formatted by the C
306 functions :c:func:`perror` under POSIX, and :c:func:`FormatMessage`
307 under Windows.
308
309 .. attribute:: filename
310 filename2
311
312 For exceptions that involve a file system path (such as :func:`open` or
313 :func:`os.unlink`), :attr:`filename` is the file name passed to the function.
314 For functions that involve two file system paths (such as
315 :func:`os.rename`), :attr:`filename2` corresponds to the second
316 file name passed to the function.
Larry Hastingsb0827312014-02-09 22:05:19 -0800317
Georg Brandl116aa622007-08-15 14:28:22 +0000318
Antoine Pitrou195e7022011-10-12 16:46:46 +0200319 .. versionchanged:: 3.3
320 :exc:`EnvironmentError`, :exc:`IOError`, :exc:`WindowsError`,
Berker Peksag8fafc742016-04-11 12:23:04 +0300321 :exc:`socket.error`, :exc:`select.error` and
Martin Panter5487c132015-10-26 11:05:42 +0000322 :exc:`mmap.error` have been merged into :exc:`OSError`, and the
323 constructor may return a subclass.
Antoine Pitrou195e7022011-10-12 16:46:46 +0200324
Victor Stinner292c8352012-10-30 02:17:38 +0100325 .. versionchanged:: 3.4
Victor Stinner292c8352012-10-30 02:17:38 +0100326 The :attr:`filename` attribute is now the original file name passed to
327 the function, instead of the name encoded to or decoded from the
Victor Stinner4b9aad42020-11-02 16:49:54 +0100328 :term:`filesystem encoding and error handler`. Also, the *filename2*
329 constructor argument and attribute was added.
Victor Stinner292c8352012-10-30 02:17:38 +0100330
Georg Brandl116aa622007-08-15 14:28:22 +0000331
332.. exception:: OverflowError
333
334 Raised when the result of an arithmetic operation is too large to be
Georg Brandlba956ae2007-11-29 17:24:34 +0000335 represented. This cannot occur for integers (which would rather raise
Terry Jan Reedyb6d1f482014-06-16 03:31:00 -0400336 :exc:`MemoryError` than give up). However, for historical reasons,
337 OverflowError is sometimes raised for integers that are outside a required
338 range. Because of the lack of standardization of floating point exception
339 handling in C, most floating point operations are not checked.
Georg Brandl116aa622007-08-15 14:28:22 +0000340
341
Yury Selivanovf488fb42015-07-03 01:04:23 -0400342.. exception:: RecursionError
343
344 This exception is derived from :exc:`RuntimeError`. It is raised when the
345 interpreter detects that the maximum recursion depth (see
346 :func:`sys.getrecursionlimit`) is exceeded.
347
348 .. versionadded:: 3.5
349 Previously, a plain :exc:`RuntimeError` was raised.
350
351
Georg Brandl116aa622007-08-15 14:28:22 +0000352.. exception:: ReferenceError
353
354 This exception is raised when a weak reference proxy, created by the
355 :func:`weakref.proxy` function, is used to access an attribute of the referent
356 after it has been garbage collected. For more information on weak references,
357 see the :mod:`weakref` module.
358
Georg Brandl116aa622007-08-15 14:28:22 +0000359
360.. exception:: RuntimeError
361
362 Raised when an error is detected that doesn't fall in any of the other
363 categories. The associated value is a string indicating what precisely went
Antoine Pitrou9527f162013-11-25 19:08:32 +0100364 wrong.
Georg Brandl116aa622007-08-15 14:28:22 +0000365
366
367.. exception:: StopIteration
368
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000369 Raised by built-in function :func:`next` and an :term:`iterator`\'s
Ezio Melotti1dd7c302012-10-12 13:45:38 +0300370 :meth:`~iterator.__next__` method to signal that there are no further
371 items produced by the iterator.
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000372
373 The exception object has a single attribute :attr:`value`, which is
374 given as an argument when constructing the exception, and defaults
375 to :const:`None`.
376
Yury Selivanov66f88282015-06-24 11:04:15 -0400377 When a :term:`generator` or :term:`coroutine` function
378 returns, a new :exc:`StopIteration` instance is
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000379 raised, and the value returned by the function is used as the
380 :attr:`value` parameter to the constructor of the exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000381
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500382 If a generator code directly or indirectly raises :exc:`StopIteration`,
383 it is converted into a :exc:`RuntimeError` (retaining the
384 :exc:`StopIteration` as the new exception's cause).
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400385
Nick Coghlan0ed80192012-01-14 14:43:24 +1000386 .. versionchanged:: 3.3
387 Added ``value`` attribute and the ability for generator functions to
388 use it to return a value.
Georg Brandl116aa622007-08-15 14:28:22 +0000389
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400390 .. versionchanged:: 3.5
Yury Selivanov43c47fe2018-01-26 15:24:24 -0500391 Introduced the RuntimeError transformation via
392 ``from __future__ import generator_stop``, see :pep:`479`.
393
394 .. versionchanged:: 3.7
395 Enable :pep:`479` for all code by default: a :exc:`StopIteration`
396 error raised in a generator is transformed into a :exc:`RuntimeError`.
Yury Selivanov8170e8c2015-05-09 11:44:30 -0400397
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400398.. exception:: StopAsyncIteration
399
400 Must be raised by :meth:`__anext__` method of an
401 :term:`asynchronous iterator` object to stop the iteration.
402
403 .. versionadded:: 3.5
Yury Selivanovf3e40fa2015-05-21 11:50:30 -0400404
Georg Brandl116aa622007-08-15 14:28:22 +0000405.. exception:: SyntaxError
406
407 Raised when the parser encounters a syntax error. This may occur in an
408 :keyword:`import` statement, in a call to the built-in functions :func:`exec`
409 or :func:`eval`, or when reading the initial script or standard input
410 (also interactively).
411
Ammar Askarb2a91e02021-04-02 17:25:31 -0400412 The :func:`str` of the exception instance returns only the error message.
413
414 .. attribute:: filename
415
416 The name of the file the syntax error occurred in.
417
418 .. attribute:: lineno
419
420 Which line number in the file the error occurred in. This is
421 1-indexed: the first line in the file has a ``lineno`` of 1.
422
423 .. attribute:: offset
424
425 The column in the line where the error occurred. This is
426 1-indexed: the first character in the line has an ``offset`` of 1.
427
428 .. attribute:: text
429
430 The source code text involved in the error.
Georg Brandl116aa622007-08-15 14:28:22 +0000431
432
Georg Brandl0bdfbfa2010-12-18 17:51:28 +0000433.. exception:: IndentationError
434
435 Base class for syntax errors related to incorrect indentation. This is a
436 subclass of :exc:`SyntaxError`.
437
438
439.. exception:: TabError
440
441 Raised when indentation contains an inconsistent use of tabs and spaces.
442 This is a subclass of :exc:`IndentationError`.
443
444
Georg Brandl116aa622007-08-15 14:28:22 +0000445.. exception:: SystemError
446
447 Raised when the interpreter finds an internal error, but the situation does not
448 look so serious to cause it to abandon all hope. The associated value is a
449 string indicating what went wrong (in low-level terms).
450
451 You should report this to the author or maintainer of your Python interpreter.
452 Be sure to report the version of the Python interpreter (``sys.version``; it is
453 also printed at the start of an interactive Python session), the exact error
454 message (the exception's associated value) and if possible the source of the
455 program that triggered the error.
456
457
458.. exception:: SystemExit
459
Berker Peksag77a6b202015-03-10 14:47:15 +0200460 This exception is raised by the :func:`sys.exit` function. It inherits from
461 :exc:`BaseException` instead of :exc:`Exception` so that it is not accidentally
462 caught by code that catches :exc:`Exception`. This allows the exception to
463 properly propagate up and cause the interpreter to exit. When it is not
464 handled, the Python interpreter exits; no stack traceback is printed. The
465 constructor accepts the same optional argument passed to :func:`sys.exit`.
466 If the value is an integer, it specifies the system exit status (passed to
467 C's :c:func:`exit` function); if it is ``None``, the exit status is zero; if
468 it has another type (such as a string), the object's value is printed and
Georg Brandl95817b32008-05-11 14:30:18 +0000469 the exit status is one.
Georg Brandl116aa622007-08-15 14:28:22 +0000470
Georg Brandl116aa622007-08-15 14:28:22 +0000471 A call to :func:`sys.exit` is translated into an exception so that clean-up
472 handlers (:keyword:`finally` clauses of :keyword:`try` statements) can be
473 executed, and so that a debugger can execute a script without running the risk
474 of losing control. The :func:`os._exit` function can be used if it is
475 absolutely positively necessary to exit immediately (for example, in the child
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300476 process after a call to :func:`os.fork`).
Georg Brandl116aa622007-08-15 14:28:22 +0000477
Berker Peksag77a6b202015-03-10 14:47:15 +0200478 .. attribute:: code
479
480 The exit status or error message that is passed to the constructor.
481 (Defaults to ``None``.)
Georg Brandl116aa622007-08-15 14:28:22 +0000482
Georg Brandl116aa622007-08-15 14:28:22 +0000483
484.. exception:: TypeError
485
486 Raised when an operation or function is applied to an object of inappropriate
487 type. The associated value is a string giving details about the type mismatch.
488
Ethan Furman20bd9f02016-08-05 15:10:16 -0700489 This exception may be raised by user code to indicate that an attempted
490 operation on an object is not supported, and is not meant to be. If an object
491 is meant to support a given operation but has not yet provided an
492 implementation, :exc:`NotImplementedError` is the proper exception to raise.
493
494 Passing arguments of the wrong type (e.g. passing a :class:`list` when an
495 :class:`int` is expected) should result in a :exc:`TypeError`, but passing
496 arguments with the wrong value (e.g. a number outside expected boundaries)
497 should result in a :exc:`ValueError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000498
499.. exception:: UnboundLocalError
500
501 Raised when a reference is made to a local variable in a function or method, but
502 no value has been bound to that variable. This is a subclass of
503 :exc:`NameError`.
504
Georg Brandl116aa622007-08-15 14:28:22 +0000505
506.. exception:: UnicodeError
507
508 Raised when a Unicode-related encoding or decoding error occurs. It is a
509 subclass of :exc:`ValueError`.
510
Benjamin Peterson78f7e3a2012-12-02 11:33:06 -0500511 :exc:`UnicodeError` has attributes that describe the encoding or decoding
512 error. For example, ``err.object[err.start:err.end]`` gives the particular
513 invalid input that the codec failed on.
514
515 .. attribute:: encoding
516
517 The name of the encoding that raised the error.
518
519 .. attribute:: reason
520
521 A string describing the specific codec error.
522
523 .. attribute:: object
524
525 The object the codec was attempting to encode or decode.
526
527 .. attribute:: start
528
529 The first index of invalid data in :attr:`object`.
530
531 .. attribute:: end
532
533 The index after the last invalid data in :attr:`object`.
534
Georg Brandl116aa622007-08-15 14:28:22 +0000535
536.. exception:: UnicodeEncodeError
537
538 Raised when a Unicode-related error occurs during encoding. It is a subclass of
539 :exc:`UnicodeError`.
540
Georg Brandl116aa622007-08-15 14:28:22 +0000541
542.. exception:: UnicodeDecodeError
543
544 Raised when a Unicode-related error occurs during decoding. It is a subclass of
545 :exc:`UnicodeError`.
546
Georg Brandl116aa622007-08-15 14:28:22 +0000547
548.. exception:: UnicodeTranslateError
549
550 Raised when a Unicode-related error occurs during translating. It is a subclass
551 of :exc:`UnicodeError`.
552
Georg Brandl116aa622007-08-15 14:28:22 +0000553
554.. exception:: ValueError
555
Raymond Hettingerfeabae92018-07-17 08:35:26 -0700556 Raised when an operation or function receives an argument that has the
Georg Brandl116aa622007-08-15 14:28:22 +0000557 right type but an inappropriate value, and the situation is not described by a
558 more precise exception such as :exc:`IndexError`.
559
560
Georg Brandl116aa622007-08-15 14:28:22 +0000561.. exception:: ZeroDivisionError
562
563 Raised when the second argument of a division or modulo operation is zero. The
564 associated value is a string indicating the type of the operands and the
565 operation.
566
Georg Brandlfbd1b222009-12-29 21:38:35 +0000567
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200568The following exceptions are kept for compatibility with previous versions;
569starting from Python 3.3, they are aliases of :exc:`OSError`.
570
571.. exception:: EnvironmentError
572
573.. exception:: IOError
574
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200575.. exception:: WindowsError
576
577 Only available on Windows.
578
579
580OS exceptions
581^^^^^^^^^^^^^
582
583The following exceptions are subclasses of :exc:`OSError`, they get raised
584depending on the system error code.
585
586.. exception:: BlockingIOError
587
588 Raised when an operation would block on an object (e.g. socket) set
589 for non-blocking operation.
590 Corresponds to :c:data:`errno` ``EAGAIN``, ``EALREADY``,
591 ``EWOULDBLOCK`` and ``EINPROGRESS``.
592
Antoine Pitrouf55011f2011-10-12 18:57:23 +0200593 In addition to those of :exc:`OSError`, :exc:`BlockingIOError` can have
594 one more attribute:
595
596 .. attribute:: characters_written
597
598 An integer containing the number of characters written to the stream
599 before it blocked. This attribute is available when using the
600 buffered I/O classes from the :mod:`io` module.
601
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200602.. exception:: ChildProcessError
603
604 Raised when an operation on a child process failed.
605 Corresponds to :c:data:`errno` ``ECHILD``.
606
607.. exception:: ConnectionError
608
Ezio Melottib24d3cf2012-10-21 03:22:05 +0300609 A base class for connection-related issues.
610
611 Subclasses are :exc:`BrokenPipeError`, :exc:`ConnectionAbortedError`,
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200612 :exc:`ConnectionRefusedError` and :exc:`ConnectionResetError`.
613
Ezio Melottib24d3cf2012-10-21 03:22:05 +0300614.. exception:: BrokenPipeError
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200615
Ezio Melottib24d3cf2012-10-21 03:22:05 +0300616 A subclass of :exc:`ConnectionError`, raised when trying to write on a
617 pipe while the other end has been closed, or trying to write on a socket
618 which has been shutdown for writing.
619 Corresponds to :c:data:`errno` ``EPIPE`` and ``ESHUTDOWN``.
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200620
Ezio Melottib24d3cf2012-10-21 03:22:05 +0300621.. exception:: ConnectionAbortedError
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200622
Ezio Melottib24d3cf2012-10-21 03:22:05 +0300623 A subclass of :exc:`ConnectionError`, raised when a connection attempt
624 is aborted by the peer.
625 Corresponds to :c:data:`errno` ``ECONNABORTED``.
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200626
Ezio Melottib24d3cf2012-10-21 03:22:05 +0300627.. exception:: ConnectionRefusedError
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200628
Ezio Melottib24d3cf2012-10-21 03:22:05 +0300629 A subclass of :exc:`ConnectionError`, raised when a connection attempt
630 is refused by the peer.
631 Corresponds to :c:data:`errno` ``ECONNREFUSED``.
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200632
Ezio Melottib24d3cf2012-10-21 03:22:05 +0300633.. exception:: ConnectionResetError
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200634
Ezio Melottib24d3cf2012-10-21 03:22:05 +0300635 A subclass of :exc:`ConnectionError`, raised when a connection is
636 reset by the peer.
637 Corresponds to :c:data:`errno` ``ECONNRESET``.
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200638
639.. exception:: FileExistsError
640
641 Raised when trying to create a file or directory which already exists.
642 Corresponds to :c:data:`errno` ``EEXIST``.
643
644.. exception:: FileNotFoundError
645
646 Raised when a file or directory is requested but doesn't exist.
647 Corresponds to :c:data:`errno` ``ENOENT``.
648
649.. exception:: InterruptedError
650
651 Raised when a system call is interrupted by an incoming signal.
Victor Stinnerf70e1ca2015-03-30 21:16:11 +0200652 Corresponds to :c:data:`errno` :py:data:`~errno.EINTR`.
653
654 .. versionchanged:: 3.5
655 Python now retries system calls when a syscall is interrupted by a
656 signal, except if the signal handler raises an exception (see :pep:`475`
657 for the rationale), instead of raising :exc:`InterruptedError`.
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200658
659.. exception:: IsADirectoryError
660
661 Raised when a file operation (such as :func:`os.remove`) is requested
662 on a directory.
663 Corresponds to :c:data:`errno` ``EISDIR``.
664
665.. exception:: NotADirectoryError
666
667 Raised when a directory operation (such as :func:`os.listdir`) is requested
668 on something which is not a directory.
669 Corresponds to :c:data:`errno` ``ENOTDIR``.
670
671.. exception:: PermissionError
672
673 Raised when trying to run an operation without the adequate access
674 rights - for example filesystem permissions.
675 Corresponds to :c:data:`errno` ``EACCES`` and ``EPERM``.
676
677.. exception:: ProcessLookupError
678
679 Raised when a given process doesn't exist.
680 Corresponds to :c:data:`errno` ``ESRCH``.
681
682.. exception:: TimeoutError
683
684 Raised when a system function timed out at the system level.
685 Corresponds to :c:data:`errno` ``ETIMEDOUT``.
686
687.. versionadded:: 3.3
688 All the above :exc:`OSError` subclasses were added.
689
690
691.. seealso::
692
693 :pep:`3151` - Reworking the OS and IO exception hierarchy
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200694
695
Nick Coghlan9b997472018-01-08 12:45:02 +1000696.. _warning-categories-as-exceptions:
697
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200698Warnings
699--------
700
Nick Coghlan9b997472018-01-08 12:45:02 +1000701The following exceptions are used as warning categories; see the
702:ref:`warning-categories` documentation for more details.
Georg Brandl116aa622007-08-15 14:28:22 +0000703
Georg Brandl116aa622007-08-15 14:28:22 +0000704.. exception:: Warning
705
706 Base class for warning categories.
707
708
709.. exception:: UserWarning
710
711 Base class for warnings generated by user code.
712
713
714.. exception:: DeprecationWarning
715
Nick Coghlan9b997472018-01-08 12:45:02 +1000716 Base class for warnings about deprecated features when those warnings are
717 intended for other Python developers.
Georg Brandl116aa622007-08-15 14:28:22 +0000718
Victor Stinnerb9783d22020-01-24 10:22:18 +0100719 Ignored by the default warning filters, except in the ``__main__`` module
720 (:pep:`565`). Enabling the :ref:`Python Development Mode <devmode>` shows
721 this warning.
722
Georg Brandl116aa622007-08-15 14:28:22 +0000723
724.. exception:: PendingDeprecationWarning
725
Inada Naokia3283ef2019-04-15 21:40:23 +0900726 Base class for warnings about features which are obsolete and
727 expected to be deprecated in the future, but are not deprecated
728 at the moment.
Georg Brandl116aa622007-08-15 14:28:22 +0000729
Inada Naokia3283ef2019-04-15 21:40:23 +0900730 This class is rarely used as emitting a warning about a possible
731 upcoming deprecation is unusual, and :exc:`DeprecationWarning`
732 is preferred for already active deprecations.
Inada Naoki176d2632019-04-05 17:54:24 +0900733
Victor Stinnerb9783d22020-01-24 10:22:18 +0100734 Ignored by the default warning filters. Enabling the :ref:`Python
735 Development Mode <devmode>` shows this warning.
736
Georg Brandl116aa622007-08-15 14:28:22 +0000737
738.. exception:: SyntaxWarning
739
Martin Panterd21e0b52015-10-10 10:36:22 +0000740 Base class for warnings about dubious syntax.
Georg Brandl116aa622007-08-15 14:28:22 +0000741
742
743.. exception:: RuntimeWarning
744
745 Base class for warnings about dubious runtime behavior.
746
747
748.. exception:: FutureWarning
749
Nick Coghlan9b997472018-01-08 12:45:02 +1000750 Base class for warnings about deprecated features when those warnings are
751 intended for end users of applications that are written in Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000752
753
754.. exception:: ImportWarning
755
756 Base class for warnings about probable mistakes in module imports.
757
Victor Stinnerb9783d22020-01-24 10:22:18 +0100758 Ignored by the default warning filters. Enabling the :ref:`Python
759 Development Mode <devmode>` shows this warning.
760
Georg Brandl116aa622007-08-15 14:28:22 +0000761
762.. exception:: UnicodeWarning
763
764 Base class for warnings related to Unicode.
765
Georg Brandl08be72d2010-10-24 15:11:22 +0000766
Inada Naoki48274832021-03-29 12:28:14 +0900767.. exception:: EncodingWarning
768
769 Base class for warnings related to encodings.
770
771 See :ref:`io-encoding-warning` for details.
772
773 .. versionadded:: 3.10
774
775
Guido van Rossum98297ee2007-11-06 21:34:58 +0000776.. exception:: BytesWarning
Georg Brandl116aa622007-08-15 14:28:22 +0000777
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300778 Base class for warnings related to :class:`bytes` and :class:`bytearray`.
Guido van Rossum98297ee2007-11-06 21:34:58 +0000779
Georg Brandl08be72d2010-10-24 15:11:22 +0000780
781.. exception:: ResourceWarning
782
Victor Stinnerb9783d22020-01-24 10:22:18 +0100783 Base class for warnings related to resource usage.
784
785 Ignored by the default warning filters. Enabling the :ref:`Python
786 Development Mode <devmode>` shows this warning.
Georg Brandl08be72d2010-10-24 15:11:22 +0000787
788 .. versionadded:: 3.2
789
790
791
Alexandre Vassalottic22c6f22009-07-21 00:51:58 +0000792Exception hierarchy
793-------------------
Guido van Rossum98297ee2007-11-06 21:34:58 +0000794
795The class hierarchy for built-in exceptions is:
Georg Brandl116aa622007-08-15 14:28:22 +0000796
797.. literalinclude:: ../../Lib/test/exception_hierarchy.txt