blob: ca8e4d8b6d152a10bb203b5f5e08eb60becc3e56 [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
31The built-in exception classes can be sub-classed to define new exceptions;
32programmers are encouraged to at least derive new exceptions from the
33:exc:`Exception` class and not :exc:`BaseException`. More information on
34defining exceptions is available in the Python Tutorial under
35:ref:`tut-userexceptions`.
36
Antoine Pitrouf9c77462011-10-12 16:02:00 +020037
38Base classes
39------------
40
Georg Brandlfbd1b222009-12-29 21:38:35 +000041The following exceptions are used mostly as base classes for other exceptions.
Georg Brandl116aa622007-08-15 14:28:22 +000042
Georg Brandl116aa622007-08-15 14:28:22 +000043.. exception:: BaseException
44
45 The base class for all built-in exceptions. It is not meant to be directly
Georg Brandlfb6fd5d2011-01-07 18:28:45 +000046 inherited by user-defined classes (for that, use :exc:`Exception`). If
Ezio Melotti985e24d2009-09-13 07:54:02 +000047 :func:`bytes` or :func:`str` is called on an instance of this class, the
Georg Brandlfb6fd5d2011-01-07 18:28:45 +000048 representation of the argument(s) to the instance are returned, or the empty
49 string when there were no arguments.
50
51 .. attribute:: args
52
53 The tuple of arguments given to the exception constructor. Some built-in
54 exceptions (like :exc:`IOError`) expect a certain number of arguments and
55 assign a special meaning to the elements of this tuple, while others are
56 usually called only with a single string giving an error message.
57
58 .. method:: with_traceback(tb)
59
60 This method sets *tb* as the new traceback for the exception and returns
61 the exception object. It is usually used in exception handling code like
62 this::
63
64 try:
65 ...
66 except SomeException:
67 tb = sys.exc_info()[2]
68 raise OtherException(...).with_traceback(tb)
Georg Brandl116aa622007-08-15 14:28:22 +000069
Georg Brandl116aa622007-08-15 14:28:22 +000070
71.. exception:: Exception
72
73 All built-in, non-system-exiting exceptions are derived from this class. All
74 user-defined exceptions should also be derived from this class.
75
Georg Brandl116aa622007-08-15 14:28:22 +000076
77.. exception:: ArithmeticError
78
79 The base class for those built-in exceptions that are raised for various
80 arithmetic errors: :exc:`OverflowError`, :exc:`ZeroDivisionError`,
81 :exc:`FloatingPointError`.
82
83
Georg Brandl0bdfbfa2010-12-18 17:51:28 +000084.. exception:: BufferError
85
86 Raised when a :ref:`buffer <bufferobjects>` related operation cannot be
87 performed.
88
89
Georg Brandl116aa622007-08-15 14:28:22 +000090.. exception:: LookupError
91
Benjamin Petersonfa0d7032009-06-01 22:42:33 +000092 The base class for the exceptions that are raised when a key or index used on
93 a mapping or sequence is invalid: :exc:`IndexError`, :exc:`KeyError`. This
94 can be raised directly by :func:`codecs.lookup`.
Georg Brandl116aa622007-08-15 14:28:22 +000095
96
Antoine Pitrouf9c77462011-10-12 16:02:00 +020097Concrete exceptions
98-------------------
Georg Brandl116aa622007-08-15 14:28:22 +000099
Georg Brandlfbd1b222009-12-29 21:38:35 +0000100The following exceptions are the exceptions that are usually raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000101
102.. exception:: AssertionError
103
104 .. index:: statement: assert
105
106 Raised when an :keyword:`assert` statement fails.
107
108
109.. exception:: AttributeError
110
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000111 Raised when an attribute reference (see :ref:`attribute-references`) or
112 assignment fails. (When an object does not support attribute references or
113 attribute assignments at all, :exc:`TypeError` is raised.)
Georg Brandl116aa622007-08-15 14:28:22 +0000114
115
116.. exception:: EOFError
117
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000118 Raised when one of the built-in functions (:func:`input` or :func:`raw_input`)
119 hits an end-of-file condition (EOF) without reading any data. (N.B.: the
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000120 :meth:`file.read` and :meth:`file.readline` methods return an empty string
121 when they hit EOF.)
Georg Brandl116aa622007-08-15 14:28:22 +0000122
123
124.. exception:: FloatingPointError
125
126 Raised when a floating point operation fails. This exception is always defined,
127 but can only be raised when Python is configured with the
Éric Araujo713d3032010-11-18 16:38:46 +0000128 ``--with-fpectl`` option, or the :const:`WANT_SIGFPE_HANDLER` symbol is
Georg Brandl116aa622007-08-15 14:28:22 +0000129 defined in the :file:`pyconfig.h` file.
130
131
132.. exception:: GeneratorExit
133
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000134 Raise when a :term:`generator`\'s :meth:`close` method is called. It
135 directly inherits from :exc:`BaseException` instead of :exc:`Exception` since
136 it is technically not an error.
Georg Brandl116aa622007-08-15 14:28:22 +0000137
Georg Brandl116aa622007-08-15 14:28:22 +0000138
Georg Brandl116aa622007-08-15 14:28:22 +0000139.. exception:: ImportError
140
141 Raised when an :keyword:`import` statement fails to find the module definition
142 or when a ``from ... import`` fails to find a name that is to be imported.
143
Georg Brandl116aa622007-08-15 14:28:22 +0000144
145.. exception:: IndexError
146
Georg Brandl95817b32008-05-11 14:30:18 +0000147 Raised when a sequence subscript is out of range. (Slice indices are
148 silently truncated to fall in the allowed range; if an index is not an
149 integer, :exc:`TypeError` is raised.)
Georg Brandl116aa622007-08-15 14:28:22 +0000150
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000151 .. XXX xref to sequences
Georg Brandl116aa622007-08-15 14:28:22 +0000152
153
154.. exception:: KeyError
155
156 Raised when a mapping (dictionary) key is not found in the set of existing keys.
157
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000158 .. XXX xref to mapping objects?
Georg Brandl116aa622007-08-15 14:28:22 +0000159
160
161.. exception:: KeyboardInterrupt
162
163 Raised when the user hits the interrupt key (normally :kbd:`Control-C` or
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000164 :kbd:`Delete`). During execution, a check for interrupts is made
165 regularly. The exception inherits from :exc:`BaseException` so as to not be
166 accidentally caught by code that catches :exc:`Exception` and thus prevent
167 the interpreter from exiting.
Georg Brandl116aa622007-08-15 14:28:22 +0000168
Georg Brandl116aa622007-08-15 14:28:22 +0000169
170.. exception:: MemoryError
171
172 Raised when an operation runs out of memory but the situation may still be
173 rescued (by deleting some objects). The associated value is a string indicating
174 what kind of (internal) operation ran out of memory. Note that because of the
Georg Brandl60203b42010-10-06 10:11:56 +0000175 underlying memory management architecture (C's :c:func:`malloc` function), the
Georg Brandl116aa622007-08-15 14:28:22 +0000176 interpreter may not always be able to completely recover from this situation; it
177 nevertheless raises an exception so that a stack traceback can be printed, in
178 case a run-away program was the cause.
179
180
181.. exception:: NameError
182
183 Raised when a local or global name is not found. This applies only to
184 unqualified names. The associated value is an error message that includes the
185 name that could not be found.
186
187
188.. exception:: NotImplementedError
189
190 This exception is derived from :exc:`RuntimeError`. In user defined base
191 classes, abstract methods should raise this exception when they require derived
192 classes to override the method.
193
Georg Brandl116aa622007-08-15 14:28:22 +0000194
195.. exception:: OSError
196
Christian Heimesa62da1d2008-01-12 19:39:10 +0000197 .. index:: module: errno
198
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200199 This exception is raised when a system function returns a system-related
200 error, including I/O failures such as "file not found" or "disk full"
201 (not for illegal argument types or other incidental errors). Often a
202 subclass of :exc:`OSError` will actually be raised as described in
203 `OS exceptions`_ below. The :attr:`errno` attribute is a numeric error
204 code from the C variable :c:data:`errno`.
Christian Heimesa62da1d2008-01-12 19:39:10 +0000205
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200206 Under Windows, the :attr:`winerror` attribute gives you the native
207 Windows error code. The :attr:`errno` attribute is then an approximate
208 translation, in POSIX terms, of that native error code.
209
210 Under all platforms, the :attr:`strerror` attribute is the corresponding
211 error message as provided by the operating system (as formatted by the C
212 functions :c:func:`perror` under POSIX, and :c:func:`FormatMessage`
213 Windows).
214
215 For exceptions that involve a file system path (such as :func:`open` or
216 :func:`os.unlink`), the exception instance will contain an additional
217 attribute, :attr:`filename`, which is the file name passed to the function.
Georg Brandl116aa622007-08-15 14:28:22 +0000218
Antoine Pitrou195e7022011-10-12 16:46:46 +0200219 .. versionchanged:: 3.3
220 :exc:`EnvironmentError`, :exc:`IOError`, :exc:`WindowsError`,
221 :exc:`VMSError`, :exc:`socket.error`, :exc:`select.error` and
222 :exc:`mmap.error` have been merged into :exc:`OSError`.
223
Georg Brandl116aa622007-08-15 14:28:22 +0000224
225.. exception:: OverflowError
226
227 Raised when the result of an arithmetic operation is too large to be
Georg Brandlba956ae2007-11-29 17:24:34 +0000228 represented. This cannot occur for integers (which would rather raise
Georg Brandl116aa622007-08-15 14:28:22 +0000229 :exc:`MemoryError` than give up). Because of the lack of standardization of
230 floating point exception handling in C, most floating point operations also
Georg Brandl81ac1ce2007-08-31 17:17:17 +0000231 aren't checked.
Georg Brandl116aa622007-08-15 14:28:22 +0000232
233
234.. exception:: ReferenceError
235
236 This exception is raised when a weak reference proxy, created by the
237 :func:`weakref.proxy` function, is used to access an attribute of the referent
238 after it has been garbage collected. For more information on weak references,
239 see the :mod:`weakref` module.
240
Georg Brandl116aa622007-08-15 14:28:22 +0000241
242.. exception:: RuntimeError
243
244 Raised when an error is detected that doesn't fall in any of the other
245 categories. The associated value is a string indicating what precisely went
246 wrong. (This exception is mostly a relic from a previous version of the
247 interpreter; it is not used very much any more.)
248
249
250.. exception:: StopIteration
251
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000252 Raised by built-in function :func:`next` and an :term:`iterator`\'s
253 :meth:`__next__` method to signal that there are no further values.
Georg Brandl116aa622007-08-15 14:28:22 +0000254
Georg Brandl116aa622007-08-15 14:28:22 +0000255
256.. exception:: SyntaxError
257
258 Raised when the parser encounters a syntax error. This may occur in an
259 :keyword:`import` statement, in a call to the built-in functions :func:`exec`
260 or :func:`eval`, or when reading the initial script or standard input
261 (also interactively).
262
Georg Brandl116aa622007-08-15 14:28:22 +0000263 Instances of this class have attributes :attr:`filename`, :attr:`lineno`,
264 :attr:`offset` and :attr:`text` for easier access to the details. :func:`str`
265 of the exception instance returns only the message.
266
267
Georg Brandl0bdfbfa2010-12-18 17:51:28 +0000268.. exception:: IndentationError
269
270 Base class for syntax errors related to incorrect indentation. This is a
271 subclass of :exc:`SyntaxError`.
272
273
274.. exception:: TabError
275
276 Raised when indentation contains an inconsistent use of tabs and spaces.
277 This is a subclass of :exc:`IndentationError`.
278
279
Georg Brandl116aa622007-08-15 14:28:22 +0000280.. exception:: SystemError
281
282 Raised when the interpreter finds an internal error, but the situation does not
283 look so serious to cause it to abandon all hope. The associated value is a
284 string indicating what went wrong (in low-level terms).
285
286 You should report this to the author or maintainer of your Python interpreter.
287 Be sure to report the version of the Python interpreter (``sys.version``; it is
288 also printed at the start of an interactive Python session), the exact error
289 message (the exception's associated value) and if possible the source of the
290 program that triggered the error.
291
292
293.. exception:: SystemExit
294
295 This exception is raised by the :func:`sys.exit` function. When it is not
296 handled, the Python interpreter exits; no stack traceback is printed. If the
Georg Brandl95817b32008-05-11 14:30:18 +0000297 associated value is an integer, it specifies the system exit status (passed
Georg Brandl60203b42010-10-06 10:11:56 +0000298 to C's :c:func:`exit` function); if it is ``None``, the exit status is zero;
Georg Brandl95817b32008-05-11 14:30:18 +0000299 if it has another type (such as a string), the object's value is printed and
300 the exit status is one.
Georg Brandl116aa622007-08-15 14:28:22 +0000301
Georg Brandl116aa622007-08-15 14:28:22 +0000302 Instances have an attribute :attr:`code` which is set to the proposed exit
303 status or error message (defaulting to ``None``). Also, this exception derives
304 directly from :exc:`BaseException` and not :exc:`Exception`, since it is not
305 technically an error.
306
307 A call to :func:`sys.exit` is translated into an exception so that clean-up
308 handlers (:keyword:`finally` clauses of :keyword:`try` statements) can be
309 executed, and so that a debugger can execute a script without running the risk
310 of losing control. The :func:`os._exit` function can be used if it is
311 absolutely positively necessary to exit immediately (for example, in the child
312 process after a call to :func:`fork`).
313
314 The exception inherits from :exc:`BaseException` instead of :exc:`Exception` so
315 that it is not accidentally caught by code that catches :exc:`Exception`. This
316 allows the exception to properly propagate up and cause the interpreter to exit.
317
Georg Brandl116aa622007-08-15 14:28:22 +0000318
319.. exception:: TypeError
320
321 Raised when an operation or function is applied to an object of inappropriate
322 type. The associated value is a string giving details about the type mismatch.
323
324
325.. exception:: UnboundLocalError
326
327 Raised when a reference is made to a local variable in a function or method, but
328 no value has been bound to that variable. This is a subclass of
329 :exc:`NameError`.
330
Georg Brandl116aa622007-08-15 14:28:22 +0000331
332.. exception:: UnicodeError
333
334 Raised when a Unicode-related encoding or decoding error occurs. It is a
335 subclass of :exc:`ValueError`.
336
Georg Brandl116aa622007-08-15 14:28:22 +0000337
338.. exception:: UnicodeEncodeError
339
340 Raised when a Unicode-related error occurs during encoding. It is a subclass of
341 :exc:`UnicodeError`.
342
Georg Brandl116aa622007-08-15 14:28:22 +0000343
344.. exception:: UnicodeDecodeError
345
346 Raised when a Unicode-related error occurs during decoding. It is a subclass of
347 :exc:`UnicodeError`.
348
Georg Brandl116aa622007-08-15 14:28:22 +0000349
350.. exception:: UnicodeTranslateError
351
352 Raised when a Unicode-related error occurs during translating. It is a subclass
353 of :exc:`UnicodeError`.
354
Georg Brandl116aa622007-08-15 14:28:22 +0000355
356.. exception:: ValueError
357
358 Raised when a built-in operation or function receives an argument that has the
359 right type but an inappropriate value, and the situation is not described by a
360 more precise exception such as :exc:`IndexError`.
361
362
Georg Brandl116aa622007-08-15 14:28:22 +0000363.. exception:: ZeroDivisionError
364
365 Raised when the second argument of a division or modulo operation is zero. The
366 associated value is a string indicating the type of the operands and the
367 operation.
368
Georg Brandlfbd1b222009-12-29 21:38:35 +0000369
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200370The following exceptions are kept for compatibility with previous versions;
371starting from Python 3.3, they are aliases of :exc:`OSError`.
372
373.. exception:: EnvironmentError
374
375.. exception:: IOError
376
377.. exception:: VMSError
378
379 Only available on VMS.
380
381.. exception:: WindowsError
382
383 Only available on Windows.
384
385
386OS exceptions
387^^^^^^^^^^^^^
388
389The following exceptions are subclasses of :exc:`OSError`, they get raised
390depending on the system error code.
391
392.. exception:: BlockingIOError
393
394 Raised when an operation would block on an object (e.g. socket) set
395 for non-blocking operation.
396 Corresponds to :c:data:`errno` ``EAGAIN``, ``EALREADY``,
397 ``EWOULDBLOCK`` and ``EINPROGRESS``.
398
Antoine Pitrouf55011f2011-10-12 18:57:23 +0200399 In addition to those of :exc:`OSError`, :exc:`BlockingIOError` can have
400 one more attribute:
401
402 .. attribute:: characters_written
403
404 An integer containing the number of characters written to the stream
405 before it blocked. This attribute is available when using the
406 buffered I/O classes from the :mod:`io` module.
407
Antoine Pitrouf9c77462011-10-12 16:02:00 +0200408.. exception:: ChildProcessError
409
410 Raised when an operation on a child process failed.
411 Corresponds to :c:data:`errno` ``ECHILD``.
412
413.. exception:: ConnectionError
414
415 A base class for connection-related issues. Subclasses are
416 :exc:`BrokenPipeError`, :exc:`ConnectionAbortedError`,
417 :exc:`ConnectionRefusedError` and :exc:`ConnectionResetError`.
418
419 .. exception:: BrokenPipeError
420
421 A subclass of :exc:`ConnectionError`, raised when trying to write on a
422 pipe while the other end has been closed, or trying to write on a socket
423 which has been shutdown for writing.
424 Corresponds to :c:data:`errno` ``EPIPE`` and ``ESHUTDOWN``.
425
426 .. exception:: ConnectionAbortedError
427
428 A subclass of :exc:`ConnectionError`, raised when a connection attempt
429 is aborted by the peer.
430 Corresponds to :c:data:`errno` ``ECONNABORTED``.
431
432 .. exception:: ConnectionRefusedError
433
434 A subclass of :exc:`ConnectionError`, raised when a connection attempt
435 is refused by the peer.
436 Corresponds to :c:data:`errno` ``ECONNREFUSED``.
437
438 .. exception:: ConnectionResetError
439
440 A subclass of :exc:`ConnectionError`, raised when a connection is
441 reset by the peer.
442 Corresponds to :c:data:`errno` ``ECONNRESET``.
443
444.. exception:: FileExistsError
445
446 Raised when trying to create a file or directory which already exists.
447 Corresponds to :c:data:`errno` ``EEXIST``.
448
449.. exception:: FileNotFoundError
450
451 Raised when a file or directory is requested but doesn't exist.
452 Corresponds to :c:data:`errno` ``ENOENT``.
453
454.. exception:: InterruptedError
455
456 Raised when a system call is interrupted by an incoming signal.
457 Corresponds to :c:data:`errno` ``EEINTR``.
458
459.. exception:: IsADirectoryError
460
461 Raised when a file operation (such as :func:`os.remove`) is requested
462 on a directory.
463 Corresponds to :c:data:`errno` ``EISDIR``.
464
465.. exception:: NotADirectoryError
466
467 Raised when a directory operation (such as :func:`os.listdir`) is requested
468 on something which is not a directory.
469 Corresponds to :c:data:`errno` ``ENOTDIR``.
470
471.. exception:: PermissionError
472
473 Raised when trying to run an operation without the adequate access
474 rights - for example filesystem permissions.
475 Corresponds to :c:data:`errno` ``EACCES`` and ``EPERM``.
476
477.. exception:: ProcessLookupError
478
479 Raised when a given process doesn't exist.
480 Corresponds to :c:data:`errno` ``ESRCH``.
481
482.. exception:: TimeoutError
483
484 Raised when a system function timed out at the system level.
485 Corresponds to :c:data:`errno` ``ETIMEDOUT``.
486
487.. versionadded:: 3.3
488 All the above :exc:`OSError` subclasses were added.
489
490
491.. seealso::
492
493 :pep:`3151` - Reworking the OS and IO exception hierarchy
494 PEP written and implemented by Antoine Pitrou.
495
496
497Warnings
498--------
499
Georg Brandl116aa622007-08-15 14:28:22 +0000500The following exceptions are used as warning categories; see the :mod:`warnings`
501module for more information.
502
Georg Brandl116aa622007-08-15 14:28:22 +0000503.. exception:: Warning
504
505 Base class for warning categories.
506
507
508.. exception:: UserWarning
509
510 Base class for warnings generated by user code.
511
512
513.. exception:: DeprecationWarning
514
515 Base class for warnings about deprecated features.
516
517
518.. exception:: PendingDeprecationWarning
519
520 Base class for warnings about features which will be deprecated in the future.
521
522
523.. exception:: SyntaxWarning
524
525 Base class for warnings about dubious syntax
526
527
528.. exception:: RuntimeWarning
529
530 Base class for warnings about dubious runtime behavior.
531
532
533.. exception:: FutureWarning
534
535 Base class for warnings about constructs that will change semantically in the
536 future.
537
538
539.. exception:: ImportWarning
540
541 Base class for warnings about probable mistakes in module imports.
542
Georg Brandl116aa622007-08-15 14:28:22 +0000543
544.. exception:: UnicodeWarning
545
546 Base class for warnings related to Unicode.
547
Georg Brandl08be72d2010-10-24 15:11:22 +0000548
Guido van Rossum98297ee2007-11-06 21:34:58 +0000549.. exception:: BytesWarning
Georg Brandl116aa622007-08-15 14:28:22 +0000550
Guido van Rossum98297ee2007-11-06 21:34:58 +0000551 Base class for warnings related to :class:`bytes` and :class:`buffer`.
552
Georg Brandl08be72d2010-10-24 15:11:22 +0000553
554.. exception:: ResourceWarning
555
556 Base class for warnings related to resource usage.
557
558 .. versionadded:: 3.2
559
560
561
Alexandre Vassalottic22c6f22009-07-21 00:51:58 +0000562Exception hierarchy
563-------------------
Guido van Rossum98297ee2007-11-06 21:34:58 +0000564
565The class hierarchy for built-in exceptions is:
Georg Brandl116aa622007-08-15 14:28:22 +0000566
567.. literalinclude:: ../../Lib/test/exception_hierarchy.txt