• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1.. _bltin-exceptions:
2
3Built-in Exceptions
4===================
5
6.. index::
7   statement: try
8   statement: except
9
10In Python, all exceptions must be instances of a class that derives from
11:class:`BaseException`.  In a :keyword:`try` statement with an :keyword:`except`
12clause 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"
21indicating 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.
25
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
31The 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
35:ref:`tut-userexceptions`.
36
37When raising (or re-raising) an exception in an :keyword:`except` or
38:keyword:`finally` clause
39: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
43When 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.
58
59The 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__`
63is :const:`None` and :attr:`__suppress_context__` is false.
64
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.
68
69
70Base classes
71------------
72
73The following exceptions are used mostly as base classes for other exceptions.
74
75.. exception:: BaseException
76
77   The base class for all built-in exceptions.  It is not meant to be directly
78   inherited by user-defined classes (for that, use :exc:`Exception`).  If
79   :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.
82
83   .. attribute:: args
84
85      The tuple of arguments given to the exception constructor.  Some built-in
86      exceptions (like :exc:`OSError`) expect a certain number of arguments and
87      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)
101
102
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
108
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
116.. exception:: BufferError
117
118   Raised when a :ref:`buffer <bufferobjects>` related operation cannot be
119   performed.
120
121
122.. exception:: LookupError
123
124   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`.
127
128
129Concrete exceptions
130-------------------
131
132The following exceptions are the exceptions that are usually raised.
133
134.. exception:: AssertionError
135
136   .. index:: statement: assert
137
138   Raised when an :keyword:`assert` statement fails.
139
140
141.. exception:: AttributeError
142
143   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.)
146
147
148.. exception:: EOFError
149
150   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.)
153
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
159   ``--with-fpectl`` option, or the :const:`WANT_SIGFPE_HANDLER` symbol is
160   defined in the :file:`pyconfig.h` file.
161
162
163.. exception:: GeneratorExit
164
165   Raised when a :term:`generator` or :term:`coroutine` is closed;
166   see :meth:`generator.close` and :meth:`coroutine.close`.  It
167   directly inherits from :exc:`BaseException` instead of :exc:`Exception` since
168   it is technically not an error.
169
170
171.. exception:: ImportError
172
173   Raised when the :keyword:`import` statement has troubles trying to
174   load a module.  Also raised when the "from list" in ``from ... import``
175   has a name that cannot be found.
176
177   The :attr:`name` and :attr:`path` attributes can be set using keyword-only
178   arguments to the constructor. When set they represent the name of the module
179   that was attempted to be imported and the path to any file which triggered
180   the exception, respectively.
181
182   .. versionchanged:: 3.3
183      Added the :attr:`name` and :attr:`path` attributes.
184
185.. exception:: ModuleNotFoundError
186
187   A subclass of :exc:`ImportError` which is raised by :keyword:`import`
188   when a module could not be located.  It is also raised when ``None``
189   is found in :data:`sys.modules`.
190
191   .. versionadded:: 3.6
192
193
194.. exception:: IndexError
195
196   Raised when a sequence subscript is out of range.  (Slice indices are
197   silently truncated to fall in the allowed range; if an index is not an
198   integer, :exc:`TypeError` is raised.)
199
200   .. XXX xref to sequences
201
202
203.. exception:: KeyError
204
205   Raised when a mapping (dictionary) key is not found in the set of existing keys.
206
207   .. XXX xref to mapping objects?
208
209
210.. exception:: KeyboardInterrupt
211
212   Raised when the user hits the interrupt key (normally :kbd:`Control-C` or
213   :kbd:`Delete`).  During execution, a check for interrupts is made
214   regularly. The exception inherits from :exc:`BaseException` so as to not be
215   accidentally caught by code that catches :exc:`Exception` and thus prevent
216   the interpreter from exiting.
217
218
219.. exception:: MemoryError
220
221   Raised when an operation runs out of memory but the situation may still be
222   rescued (by deleting some objects).  The associated value is a string indicating
223   what kind of (internal) operation ran out of memory. Note that because of the
224   underlying memory management architecture (C's :c:func:`malloc` function), the
225   interpreter may not always be able to completely recover from this situation; it
226   nevertheless raises an exception so that a stack traceback can be printed, in
227   case a run-away program was the cause.
228
229
230.. exception:: NameError
231
232   Raised when a local or global name is not found.  This applies only to
233   unqualified names.  The associated value is an error message that includes the
234   name that could not be found.
235
236
237.. exception:: NotImplementedError
238
239   This exception is derived from :exc:`RuntimeError`.  In user defined base
240   classes, abstract methods should raise this exception when they require
241   derived classes to override the method, or while the class is being
242   developed to indicate that the real implementation still needs to be added.
243
244   .. note::
245
246      It should not be used to indicate that an operater or method is not
247      meant to be supported at all -- in that case either leave the operator /
248      method undefined or, if a subclass, set it to :data:`None`.
249
250   .. note::
251
252      ``NotImplementedError`` and ``NotImplemented`` are not interchangeable,
253      even though they have similar names and purposes.  See
254      :data:`NotImplemented` for details on when to use it.
255
256.. exception:: OSError([arg])
257               OSError(errno, strerror[, filename[, winerror[, filename2]]])
258
259   .. index:: module: errno
260
261   This exception is raised when a system function returns a system-related
262   error, including I/O failures such as "file not found" or "disk full"
263   (not for illegal argument types or other incidental errors).
264
265   The second form of the constructor sets the corresponding attributes,
266   described below.  The attributes default to :const:`None` if not
267   specified.  For backwards compatibility, if three arguments are passed,
268   the :attr:`~BaseException.args` attribute contains only a 2-tuple
269   of the first two constructor arguments.
270
271   The constructor often actually returns a subclass of :exc:`OSError`, as
272   described in `OS exceptions`_ below.  The particular subclass depends on
273   the final :attr:`.errno` value.  This behaviour only occurs when
274   constructing :exc:`OSError` directly or via an alias, and is not
275   inherited when subclassing.
276
277   .. attribute:: errno
278
279      A numeric error code from the C variable :c:data:`errno`.
280
281   .. attribute:: winerror
282
283      Under Windows, this gives you the native
284      Windows error code.  The :attr:`.errno` attribute is then an approximate
285      translation, in POSIX terms, of that native error code.
286
287      Under Windows, if the *winerror* constructor argument is an integer,
288      the :attr:`.errno` attribute is determined from the Windows error code,
289      and the *errno* argument is ignored.  On other platforms, the
290      *winerror* argument is ignored, and the :attr:`winerror` attribute
291      does not exist.
292
293   .. attribute:: strerror
294
295      The corresponding error message, as provided by
296      the operating system.  It is formatted by the C
297      functions :c:func:`perror` under POSIX, and :c:func:`FormatMessage`
298      under Windows.
299
300   .. attribute:: filename
301                  filename2
302
303      For exceptions that involve a file system path (such as :func:`open` or
304      :func:`os.unlink`), :attr:`filename` is the file name passed to the function.
305      For functions that involve two file system paths (such as
306      :func:`os.rename`), :attr:`filename2` corresponds to the second
307      file name passed to the function.
308
309
310   .. versionchanged:: 3.3
311      :exc:`EnvironmentError`, :exc:`IOError`, :exc:`WindowsError`,
312      :exc:`socket.error`, :exc:`select.error` and
313      :exc:`mmap.error` have been merged into :exc:`OSError`, and the
314      constructor may return a subclass.
315
316   .. versionchanged:: 3.4
317      The :attr:`filename` attribute is now the original file name passed to
318      the function, instead of the name encoded to or decoded from the
319      filesystem encoding.  Also, the *filename2* constructor argument and
320      attribute was added.
321
322
323.. exception:: OverflowError
324
325   Raised when the result of an arithmetic operation is too large to be
326   represented.  This cannot occur for integers (which would rather raise
327   :exc:`MemoryError` than give up).  However, for historical reasons,
328   OverflowError is sometimes raised for integers that are outside a required
329   range.   Because of the lack of standardization of floating point exception
330   handling in C, most floating point operations are not checked.
331
332
333.. exception:: RecursionError
334
335   This exception is derived from :exc:`RuntimeError`.  It is raised when the
336   interpreter detects that the maximum recursion depth (see
337   :func:`sys.getrecursionlimit`) is exceeded.
338
339   .. versionadded:: 3.5
340      Previously, a plain :exc:`RuntimeError` was raised.
341
342
343.. exception:: ReferenceError
344
345   This exception is raised when a weak reference proxy, created by the
346   :func:`weakref.proxy` function, is used to access an attribute of the referent
347   after it has been garbage collected. For more information on weak references,
348   see the :mod:`weakref` module.
349
350
351.. exception:: RuntimeError
352
353   Raised when an error is detected that doesn't fall in any of the other
354   categories.  The associated value is a string indicating what precisely went
355   wrong.
356
357
358.. exception:: StopIteration
359
360   Raised by built-in function :func:`next` and an :term:`iterator`\'s
361   :meth:`~iterator.__next__` method to signal that there are no further
362   items produced by the iterator.
363
364   The exception object has a single attribute :attr:`value`, which is
365   given as an argument when constructing the exception, and defaults
366   to :const:`None`.
367
368   When a :term:`generator` or :term:`coroutine` function
369   returns, a new :exc:`StopIteration` instance is
370   raised, and the value returned by the function is used as the
371   :attr:`value` parameter to the constructor of the exception.
372
373   If a generator function defined in the presence of a ``from __future__
374   import generator_stop`` directive raises :exc:`StopIteration`, it will be
375   converted into a :exc:`RuntimeError` (retaining the :exc:`StopIteration`
376   as the new exception's cause).
377
378   .. versionchanged:: 3.3
379      Added ``value`` attribute and the ability for generator functions to
380      use it to return a value.
381
382   .. versionchanged:: 3.5
383      Introduced the RuntimeError transformation.
384
385.. exception:: StopAsyncIteration
386
387   Must be raised by :meth:`__anext__` method of an
388   :term:`asynchronous iterator` object to stop the iteration.
389
390   .. versionadded:: 3.5
391
392.. exception:: SyntaxError
393
394   Raised when the parser encounters a syntax error.  This may occur in an
395   :keyword:`import` statement, in a call to the built-in functions :func:`exec`
396   or :func:`eval`, or when reading the initial script or standard input
397   (also interactively).
398
399   Instances of this class have attributes :attr:`filename`, :attr:`lineno`,
400   :attr:`offset` and :attr:`text` for easier access to the details.  :func:`str`
401   of the exception instance returns only the message.
402
403
404.. exception:: IndentationError
405
406   Base class for syntax errors related to incorrect indentation.  This is a
407   subclass of :exc:`SyntaxError`.
408
409
410.. exception:: TabError
411
412   Raised when indentation contains an inconsistent use of tabs and spaces.
413   This is a subclass of :exc:`IndentationError`.
414
415
416.. exception:: SystemError
417
418   Raised when the interpreter finds an internal error, but the situation does not
419   look so serious to cause it to abandon all hope. The associated value is a
420   string indicating what went wrong (in low-level terms).
421
422   You should report this to the author or maintainer of your Python interpreter.
423   Be sure to report the version of the Python interpreter (``sys.version``; it is
424   also printed at the start of an interactive Python session), the exact error
425   message (the exception's associated value) and if possible the source of the
426   program that triggered the error.
427
428
429.. exception:: SystemExit
430
431   This exception is raised by the :func:`sys.exit` function.  It inherits from
432   :exc:`BaseException` instead of :exc:`Exception` so that it is not accidentally
433   caught by code that catches :exc:`Exception`.  This allows the exception to
434   properly propagate up and cause the interpreter to exit.  When it is not
435   handled, the Python interpreter exits; no stack traceback is printed.  The
436   constructor accepts the same optional argument passed to :func:`sys.exit`.
437   If the value is an integer, it specifies the system exit status (passed to
438   C's :c:func:`exit` function); if it is ``None``, the exit status is zero; if
439   it has another type (such as a string), the object's value is printed and
440   the exit status is one.
441
442   A call to :func:`sys.exit` is translated into an exception so that clean-up
443   handlers (:keyword:`finally` clauses of :keyword:`try` statements) can be
444   executed, and so that a debugger can execute a script without running the risk
445   of losing control.  The :func:`os._exit` function can be used if it is
446   absolutely positively necessary to exit immediately (for example, in the child
447   process after a call to :func:`os.fork`).
448
449   .. attribute:: code
450
451      The exit status or error message that is passed to the constructor.
452      (Defaults to ``None``.)
453
454
455.. exception:: TypeError
456
457   Raised when an operation or function is applied to an object of inappropriate
458   type.  The associated value is a string giving details about the type mismatch.
459
460   This exception may be raised by user code to indicate that an attempted
461   operation on an object is not supported, and is not meant to be. If an object
462   is meant to support a given operation but has not yet provided an
463   implementation, :exc:`NotImplementedError` is the proper exception to raise.
464
465   Passing arguments of the wrong type (e.g. passing a :class:`list` when an
466   :class:`int` is expected) should result in a :exc:`TypeError`, but passing
467   arguments with the wrong value (e.g. a number outside expected boundaries)
468   should result in a :exc:`ValueError`.
469
470.. exception:: UnboundLocalError
471
472   Raised when a reference is made to a local variable in a function or method, but
473   no value has been bound to that variable.  This is a subclass of
474   :exc:`NameError`.
475
476
477.. exception:: UnicodeError
478
479   Raised when a Unicode-related encoding or decoding error occurs.  It is a
480   subclass of :exc:`ValueError`.
481
482   :exc:`UnicodeError` has attributes that describe the encoding or decoding
483   error.  For example, ``err.object[err.start:err.end]`` gives the particular
484   invalid input that the codec failed on.
485
486   .. attribute:: encoding
487
488       The name of the encoding that raised the error.
489
490   .. attribute:: reason
491
492       A string describing the specific codec error.
493
494   .. attribute:: object
495
496       The object the codec was attempting to encode or decode.
497
498   .. attribute:: start
499
500       The first index of invalid data in :attr:`object`.
501
502   .. attribute:: end
503
504       The index after the last invalid data in :attr:`object`.
505
506
507.. exception:: UnicodeEncodeError
508
509   Raised when a Unicode-related error occurs during encoding.  It is a subclass of
510   :exc:`UnicodeError`.
511
512
513.. exception:: UnicodeDecodeError
514
515   Raised when a Unicode-related error occurs during decoding.  It is a subclass of
516   :exc:`UnicodeError`.
517
518
519.. exception:: UnicodeTranslateError
520
521   Raised when a Unicode-related error occurs during translating.  It is a subclass
522   of :exc:`UnicodeError`.
523
524
525.. exception:: ValueError
526
527   Raised when a built-in operation or function receives an argument that has the
528   right type but an inappropriate value, and the situation is not described by a
529   more precise exception such as :exc:`IndexError`.
530
531
532.. exception:: ZeroDivisionError
533
534   Raised when the second argument of a division or modulo operation is zero.  The
535   associated value is a string indicating the type of the operands and the
536   operation.
537
538
539The following exceptions are kept for compatibility with previous versions;
540starting from Python 3.3, they are aliases of :exc:`OSError`.
541
542.. exception:: EnvironmentError
543
544.. exception:: IOError
545
546.. exception:: WindowsError
547
548   Only available on Windows.
549
550
551OS exceptions
552^^^^^^^^^^^^^
553
554The following exceptions are subclasses of :exc:`OSError`, they get raised
555depending on the system error code.
556
557.. exception:: BlockingIOError
558
559   Raised when an operation would block on an object (e.g. socket) set
560   for non-blocking operation.
561   Corresponds to :c:data:`errno` ``EAGAIN``, ``EALREADY``,
562   ``EWOULDBLOCK`` and ``EINPROGRESS``.
563
564   In addition to those of :exc:`OSError`, :exc:`BlockingIOError` can have
565   one more attribute:
566
567   .. attribute:: characters_written
568
569      An integer containing the number of characters written to the stream
570      before it blocked.  This attribute is available when using the
571      buffered I/O classes from the :mod:`io` module.
572
573.. exception:: ChildProcessError
574
575   Raised when an operation on a child process failed.
576   Corresponds to :c:data:`errno` ``ECHILD``.
577
578.. exception:: ConnectionError
579
580   A base class for connection-related issues.
581
582   Subclasses are :exc:`BrokenPipeError`, :exc:`ConnectionAbortedError`,
583   :exc:`ConnectionRefusedError` and :exc:`ConnectionResetError`.
584
585.. exception:: BrokenPipeError
586
587   A subclass of :exc:`ConnectionError`, raised when trying to write on a
588   pipe while the other end has been closed, or trying to write on a socket
589   which has been shutdown for writing.
590   Corresponds to :c:data:`errno` ``EPIPE`` and ``ESHUTDOWN``.
591
592.. exception:: ConnectionAbortedError
593
594   A subclass of :exc:`ConnectionError`, raised when a connection attempt
595   is aborted by the peer.
596   Corresponds to :c:data:`errno` ``ECONNABORTED``.
597
598.. exception:: ConnectionRefusedError
599
600   A subclass of :exc:`ConnectionError`, raised when a connection attempt
601   is refused by the peer.
602   Corresponds to :c:data:`errno` ``ECONNREFUSED``.
603
604.. exception:: ConnectionResetError
605
606   A subclass of :exc:`ConnectionError`, raised when a connection is
607   reset by the peer.
608   Corresponds to :c:data:`errno` ``ECONNRESET``.
609
610.. exception:: FileExistsError
611
612   Raised when trying to create a file or directory which already exists.
613   Corresponds to :c:data:`errno` ``EEXIST``.
614
615.. exception:: FileNotFoundError
616
617   Raised when a file or directory is requested but doesn't exist.
618   Corresponds to :c:data:`errno` ``ENOENT``.
619
620.. exception:: InterruptedError
621
622   Raised when a system call is interrupted by an incoming signal.
623   Corresponds to :c:data:`errno` :py:data:`~errno.EINTR`.
624
625   .. versionchanged:: 3.5
626      Python now retries system calls when a syscall is interrupted by a
627      signal, except if the signal handler raises an exception (see :pep:`475`
628      for the rationale), instead of raising :exc:`InterruptedError`.
629
630.. exception:: IsADirectoryError
631
632   Raised when a file operation (such as :func:`os.remove`) is requested
633   on a directory.
634   Corresponds to :c:data:`errno` ``EISDIR``.
635
636.. exception:: NotADirectoryError
637
638   Raised when a directory operation (such as :func:`os.listdir`) is requested
639   on something which is not a directory.
640   Corresponds to :c:data:`errno` ``ENOTDIR``.
641
642.. exception:: PermissionError
643
644   Raised when trying to run an operation without the adequate access
645   rights - for example filesystem permissions.
646   Corresponds to :c:data:`errno` ``EACCES`` and ``EPERM``.
647
648.. exception:: ProcessLookupError
649
650   Raised when a given process doesn't exist.
651   Corresponds to :c:data:`errno` ``ESRCH``.
652
653.. exception:: TimeoutError
654
655   Raised when a system function timed out at the system level.
656   Corresponds to :c:data:`errno` ``ETIMEDOUT``.
657
658.. versionadded:: 3.3
659   All the above :exc:`OSError` subclasses were added.
660
661
662.. seealso::
663
664   :pep:`3151` - Reworking the OS and IO exception hierarchy
665
666
667Warnings
668--------
669
670The following exceptions are used as warning categories; see the :mod:`warnings`
671module for more information.
672
673.. exception:: Warning
674
675   Base class for warning categories.
676
677
678.. exception:: UserWarning
679
680   Base class for warnings generated by user code.
681
682
683.. exception:: DeprecationWarning
684
685   Base class for warnings about deprecated features.
686
687
688.. exception:: PendingDeprecationWarning
689
690   Base class for warnings about features which will be deprecated in the future.
691
692
693.. exception:: SyntaxWarning
694
695   Base class for warnings about dubious syntax.
696
697
698.. exception:: RuntimeWarning
699
700   Base class for warnings about dubious runtime behavior.
701
702
703.. exception:: FutureWarning
704
705   Base class for warnings about constructs that will change semantically in the
706   future.
707
708
709.. exception:: ImportWarning
710
711   Base class for warnings about probable mistakes in module imports.
712
713
714.. exception:: UnicodeWarning
715
716   Base class for warnings related to Unicode.
717
718
719.. exception:: BytesWarning
720
721   Base class for warnings related to :class:`bytes` and :class:`bytearray`.
722
723
724.. exception:: ResourceWarning
725
726   Base class for warnings related to resource usage.
727
728   .. versionadded:: 3.2
729
730
731
732Exception hierarchy
733-------------------
734
735The class hierarchy for built-in exceptions is:
736
737.. literalinclude:: ../../Lib/test/exception_hierarchy.txt
738