Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(35629)

Delta Between Two Patch Sets: Doc/library/exceptions.rst

Issue 11682: PEP 380 reference implementation for 3.3
Left Patch Set: Created 7 years, 8 months ago
Right Patch Set: Created 7 years, 4 months ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
Left: Side by side diff | Download
Right: Side by side diff | Download
« no previous file with change/comment | « Doc/library/dis.rst ('k') | Doc/reference/expressions.rst » ('j') | no next file with change/comment »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
LEFTRIGHT
1 .. _bltin-exceptions: 1 .. _bltin-exceptions:
2 2
3 Built-in Exceptions 3 Built-in Exceptions
4 =================== 4 ===================
5 5
6 .. index:: 6 .. index::
7 statement: try 7 statement: try
8 statement: except 8 statement: except
9 9
10 In Python, all exceptions must be instances of a class that derives from 10 In Python, all exceptions must be instances of a class that derives from
(...skipping 16 matching lines...) Expand all
27 handler or to report an error condition "just like" the situation in which the 27 handler or to report an error condition "just like" the situation in which the
28 interpreter raises the same exception; but beware that there is nothing to 28 interpreter raises the same exception; but beware that there is nothing to
29 prevent user code from raising an inappropriate error. 29 prevent user code from raising an inappropriate error.
30 30
31 The built-in exception classes can be sub-classed to define new exceptions; 31 The built-in exception classes can be sub-classed to define new exceptions;
32 programmers are encouraged to at least derive new exceptions from the 32 programmers are encouraged to at least derive new exceptions from the
33 :exc:`Exception` class and not :exc:`BaseException`. More information on 33 :exc:`Exception` class and not :exc:`BaseException`. More information on
34 defining exceptions is available in the Python Tutorial under 34 defining exceptions is available in the Python Tutorial under
35 :ref:`tut-userexceptions`. 35 :ref:`tut-userexceptions`.
36 36
37
38 Base classes
39 ------------
40
37 The following exceptions are used mostly as base classes for other exceptions. 41 The following exceptions are used mostly as base classes for other exceptions.
38 42
39 .. exception:: BaseException 43 .. exception:: BaseException
40 44
41 The base class for all built-in exceptions. It is not meant to be directly 45 The base class for all built-in exceptions. It is not meant to be directly
42 inherited by user-defined classes (for that, use :exc:`Exception`). If 46 inherited by user-defined classes (for that, use :exc:`Exception`). If
43 :func:`bytes` or :func:`str` is called on an instance of this class, the 47 :func:`str` is called on an instance of this class, the representation of
44 representation of the argument(s) to the instance are returned, or the empty 48 the argument(s) to the instance are returned, or the empty string when
45 string when there were no arguments. 49 there were no arguments.
46 50
47 .. attribute:: args 51 .. attribute:: args
48 52
49 The tuple of arguments given to the exception constructor. Some built-in 53 The tuple of arguments given to the exception constructor. Some built-in
50 exceptions (like :exc:`IOError`) expect a certain number of arguments and 54 exceptions (like :exc:`IOError`) expect a certain number of arguments and
51 assign a special meaning to the elements of this tuple, while others are 55 assign a special meaning to the elements of this tuple, while others are
52 usually called only with a single string giving an error message. 56 usually called only with a single string giving an error message.
53 57
54 .. method:: with_traceback(tb) 58 .. method:: with_traceback(tb)
55 59
(...skipping 27 matching lines...) Expand all
83 performed. 87 performed.
84 88
85 89
86 .. exception:: LookupError 90 .. exception:: LookupError
87 91
88 The base class for the exceptions that are raised when a key or index used on 92 The base class for the exceptions that are raised when a key or index used on
89 a mapping or sequence is invalid: :exc:`IndexError`, :exc:`KeyError`. This 93 a mapping or sequence is invalid: :exc:`IndexError`, :exc:`KeyError`. This
90 can be raised directly by :func:`codecs.lookup`. 94 can be raised directly by :func:`codecs.lookup`.
91 95
92 96
93 .. exception:: EnvironmentError 97 Concrete exceptions
94 98 -------------------
95 The base class for exceptions that can occur outside the Python system:
96 :exc:`IOError`, :exc:`OSError`. When exceptions of this type are created wit h a
97 2-tuple, the first item is available on the instance's :attr:`errno` attribut e
98 (it is assumed to be an error number), and the second item is available on th e
99 :attr:`strerror` attribute (it is usually the associated error message). The
100 tuple itself is also available on the :attr:`args` attribute.
101
102 When an :exc:`EnvironmentError` exception is instantiated with a 3-tuple, the
103 first two items are available as above, while the third item is available on the
104 :attr:`filename` attribute. However, for backwards compatibility, the
105 :attr:`args` attribute contains only a 2-tuple of the first two constructor
106 arguments.
107
108 The :attr:`filename` attribute is ``None`` when this exception is created wit h
109 other than 3 arguments. The :attr:`errno` and :attr:`strerror` attributes ar e
110 also ``None`` when the instance was created with other than 2 or 3 arguments.
111 In this last case, :attr:`args` contains the verbatim constructor arguments a s a
112 tuple.
113
114 99
115 The following exceptions are the exceptions that are usually raised. 100 The following exceptions are the exceptions that are usually raised.
116 101
117 .. exception:: AssertionError 102 .. exception:: AssertionError
118 103
119 .. index:: statement: assert 104 .. index:: statement: assert
120 105
121 Raised when an :keyword:`assert` statement fails. 106 Raised when an :keyword:`assert` statement fails.
122 107
123 108
(...skipping 18 matching lines...) Expand all
142 but can only be raised when Python is configured with the 127 but can only be raised when Python is configured with the
143 ``--with-fpectl`` option, or the :const:`WANT_SIGFPE_HANDLER` symbol is 128 ``--with-fpectl`` option, or the :const:`WANT_SIGFPE_HANDLER` symbol is
144 defined in the :file:`pyconfig.h` file. 129 defined in the :file:`pyconfig.h` file.
145 130
146 131
147 .. exception:: GeneratorExit 132 .. exception:: GeneratorExit
148 133
149 Raise when a :term:`generator`\'s :meth:`close` method is called. It 134 Raise when a :term:`generator`\'s :meth:`close` method is called. It
150 directly inherits from :exc:`BaseException` instead of :exc:`Exception` since 135 directly inherits from :exc:`BaseException` instead of :exc:`Exception` since
151 it is technically not an error. 136 it is technically not an error.
152
153
154 .. exception:: IOError
155
156 Raised when an I/O operation (such as the built-in :func:`print` or
157 :func:`open` functions or a method of a :term:`file object`) fails for an
158 I/O-related reason, e.g., "file not found" or "disk full".
159
160 This class is derived from :exc:`EnvironmentError`. See the discussion above
161 for more information on exception instance attributes.
162 137
163 138
164 .. exception:: ImportError 139 .. exception:: ImportError
165 140
166 Raised when an :keyword:`import` statement fails to find the module definitio n 141 Raised when an :keyword:`import` statement fails to find the module definitio n
167 or when a ``from ... import`` fails to find a name that is to be imported. 142 or when a ``from ... import`` fails to find a name that is to be imported.
168 143
169 144
170 .. exception:: IndexError 145 .. exception:: IndexError
171 146
(...skipping 42 matching lines...) Expand 10 before | Expand all | Expand 10 after
214 189
215 This exception is derived from :exc:`RuntimeError`. In user defined base 190 This exception is derived from :exc:`RuntimeError`. In user defined base
216 classes, abstract methods should raise this exception when they require deriv ed 191 classes, abstract methods should raise this exception when they require deriv ed
217 classes to override the method. 192 classes to override the method.
218 193
219 194
220 .. exception:: OSError 195 .. exception:: OSError
221 196
222 .. index:: module: errno 197 .. index:: module: errno
223 198
224 This exception is derived from :exc:`EnvironmentError`. It is raised when a 199 This exception is raised when a system function returns a system-related
225 function returns a system-related error (not for illegal argument types or 200 error, including I/O failures such as "file not found" or "disk full"
226 other incidental errors). The :attr:`errno` attribute is a numeric error 201 (not for illegal argument types or other incidental errors). Often a
227 code from :c:data:`errno`, and the :attr:`strerror` attribute is the 202 subclass of :exc:`OSError` will actually be raised as described in
228 corresponding string, as would be printed by the C function :c:func:`perror`. 203 `OS exceptions`_ below. The :attr:`errno` attribute is a numeric error
229 See the module :mod:`errno`, which contains names for the error codes defined 204 code from the C variable :c:data:`errno`.
230 by the underlying operating system. 205
231 206 Under Windows, the :attr:`winerror` attribute gives you the native
232 For exceptions that involve a file system path (such as :func:`chdir` or 207 Windows error code. The :attr:`errno` attribute is then an approximate
233 :func:`unlink`), the exception instance will contain a third attribute, 208 translation, in POSIX terms, of that native error code.
234 :attr:`filename`, which is the file name passed to the function. 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.
218
219 .. 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`.
235 223
236 224
237 .. exception:: OverflowError 225 .. exception:: OverflowError
238 226
239 Raised when the result of an arithmetic operation is too large to be 227 Raised when the result of an arithmetic operation is too large to be
240 represented. This cannot occur for integers (which would rather raise 228 represented. This cannot occur for integers (which would rather raise
241 :exc:`MemoryError` than give up). Because of the lack of standardization of 229 :exc:`MemoryError` than give up). Because of the lack of standardization of
242 floating point exception handling in C, most floating point operations also 230 floating point exception handling in C, most floating point operations also
243 aren't checked. 231 aren't checked.
244 232
(...skipping 10 matching lines...) Expand all
255 243
256 Raised when an error is detected that doesn't fall in any of the other 244 Raised when an error is detected that doesn't fall in any of the other
257 categories. The associated value is a string indicating what precisely went 245 categories. The associated value is a string indicating what precisely went
258 wrong. (This exception is mostly a relic from a previous version of the 246 wrong. (This exception is mostly a relic from a previous version of the
259 interpreter; it is not used very much any more.) 247 interpreter; it is not used very much any more.)
260 248
261 249
262 .. exception:: StopIteration 250 .. exception:: StopIteration
263 251
264 Raised by built-in function :func:`next` and an :term:`iterator`\'s 252 Raised by built-in function :func:`next` and an :term:`iterator`\'s
265 :obj:`~iterator.__next__` method to signal that there are no 253 :meth:`__next__` method to signal that there are no further items to be
266 further items in the sequence. 254 produced by the iterator.
eric.araujo 2011/09/21 16:25:47 Please use “elements”; the doc is very careful to
267 255
268 The exception object has a single attribute :attr:`value`, which is 256 The exception object has a single attribute :attr:`value`, which is
269 given as an argument when constructing the exception, and defaults 257 given as an argument when constructing the exception, and defaults
270 to :const:`None`. When a generator function returns, a 258 to :const:`None`.
eric.araujo 2011/09/21 16:25:47 Should be ``None``.
271 :exc:`StopIteration` is raised, and the value returned by the 259
272 function is used as the :attr:`value` parameter to the constructor 260 When a generator function returns, a new :exc:`StopIteration` instance is
273 of the exception. 261 raised, and the value returned by the function is used as the
262 :attr:`value` parameter to the constructor of the exception.
263
274 264
275 .. exception:: SyntaxError 265 .. exception:: SyntaxError
276 266
277 Raised when the parser encounters a syntax error. This may occur in an 267 Raised when the parser encounters a syntax error. This may occur in an
278 :keyword:`import` statement, in a call to the built-in functions :func:`exec` 268 :keyword:`import` statement, in a call to the built-in functions :func:`exec`
279 or :func:`eval`, or when reading the initial script or standard input 269 or :func:`eval`, or when reading the initial script or standard input
280 (also interactively). 270 (also interactively).
281 271
282 Instances of this class have attributes :attr:`filename`, :attr:`lineno`, 272 Instances of this class have attributes :attr:`filename`, :attr:`lineno`,
283 :attr:`offset` and :attr:`text` for easier access to the details. :func:`str ` 273 :attr:`offset` and :attr:`text` for easier access to the details. :func:`str `
(...skipping 88 matching lines...) Expand 10 before | Expand all | Expand 10 after
372 of :exc:`UnicodeError`. 362 of :exc:`UnicodeError`.
373 363
374 364
375 .. exception:: ValueError 365 .. exception:: ValueError
376 366
377 Raised when a built-in operation or function receives an argument that has th e 367 Raised when a built-in operation or function receives an argument that has th e
378 right type but an inappropriate value, and the situation is not described by a 368 right type but an inappropriate value, and the situation is not described by a
379 more precise exception such as :exc:`IndexError`. 369 more precise exception such as :exc:`IndexError`.
380 370
381 371
382 .. exception:: VMSError
383
384 Only available on VMS. Raised when a VMS-specific error occurs.
385
386
387 .. exception:: WindowsError
388
389 Raised when a Windows-specific error occurs or when the error number does not
390 correspond to an :c:data:`errno` value. The :attr:`winerror` and
391 :attr:`strerror` values are created from the return values of the
392 :c:func:`GetLastError` and :c:func:`FormatMessage` functions from the Windows
393 Platform API. The :attr:`errno` value maps the :attr:`winerror` value to
394 corresponding ``errno.h`` values. This is a subclass of :exc:`OSError`.
395
396
397 .. exception:: ZeroDivisionError 372 .. exception:: ZeroDivisionError
398 373
399 Raised when the second argument of a division or modulo operation is zero. T he 374 Raised when the second argument of a division or modulo operation is zero. T he
400 associated value is a string indicating the type of the operands and the 375 associated value is a string indicating the type of the operands and the
401 operation. 376 operation.
402 377
403 378
379 The following exceptions are kept for compatibility with previous versions;
380 starting from Python 3.3, they are aliases of :exc:`OSError`.
381
382 .. exception:: EnvironmentError
383
384 .. exception:: IOError
385
386 .. exception:: VMSError
387
388 Only available on VMS.
389
390 .. exception:: WindowsError
391
392 Only available on Windows.
393
394
395 OS exceptions
396 ^^^^^^^^^^^^^
397
398 The following exceptions are subclasses of :exc:`OSError`, they get raised
399 depending on the system error code.
400
401 .. exception:: BlockingIOError
402
403 Raised when an operation would block on an object (e.g. socket) set
404 for non-blocking operation.
405 Corresponds to :c:data:`errno` ``EAGAIN``, ``EALREADY``,
406 ``EWOULDBLOCK`` and ``EINPROGRESS``.
407
408 In addition to those of :exc:`OSError`, :exc:`BlockingIOError` can have
409 one more attribute:
410
411 .. attribute:: characters_written
412
413 An integer containing the number of characters written to the stream
414 before it blocked. This attribute is available when using the
415 buffered I/O classes from the :mod:`io` module.
416
417 .. exception:: ChildProcessError
418
419 Raised when an operation on a child process failed.
420 Corresponds to :c:data:`errno` ``ECHILD``.
421
422 .. exception:: ConnectionError
423
424 A base class for connection-related issues. Subclasses are
425 :exc:`BrokenPipeError`, :exc:`ConnectionAbortedError`,
426 :exc:`ConnectionRefusedError` and :exc:`ConnectionResetError`.
427
428 .. exception:: BrokenPipeError
429
430 A subclass of :exc:`ConnectionError`, raised when trying to write on a
431 pipe while the other end has been closed, or trying to write on a socket
432 which has been shutdown for writing.
433 Corresponds to :c:data:`errno` ``EPIPE`` and ``ESHUTDOWN``.
434
435 .. exception:: ConnectionAbortedError
436
437 A subclass of :exc:`ConnectionError`, raised when a connection attempt
438 is aborted by the peer.
439 Corresponds to :c:data:`errno` ``ECONNABORTED``.
440
441 .. exception:: ConnectionRefusedError
442
443 A subclass of :exc:`ConnectionError`, raised when a connection attempt
444 is refused by the peer.
445 Corresponds to :c:data:`errno` ``ECONNREFUSED``.
446
447 .. exception:: ConnectionResetError
448
449 A subclass of :exc:`ConnectionError`, raised when a connection is
450 reset by the peer.
451 Corresponds to :c:data:`errno` ``ECONNRESET``.
452
453 .. exception:: FileExistsError
454
455 Raised when trying to create a file or directory which already exists.
456 Corresponds to :c:data:`errno` ``EEXIST``.
457
458 .. exception:: FileNotFoundError
459
460 Raised when a file or directory is requested but doesn't exist.
461 Corresponds to :c:data:`errno` ``ENOENT``.
462
463 .. exception:: InterruptedError
464
465 Raised when a system call is interrupted by an incoming signal.
466 Corresponds to :c:data:`errno` ``EEINTR``.
467
468 .. exception:: IsADirectoryError
469
470 Raised when a file operation (such as :func:`os.remove`) is requested
471 on a directory.
472 Corresponds to :c:data:`errno` ``EISDIR``.
473
474 .. exception:: NotADirectoryError
475
476 Raised when a directory operation (such as :func:`os.listdir`) is requested
477 on something which is not a directory.
478 Corresponds to :c:data:`errno` ``ENOTDIR``.
479
480 .. exception:: PermissionError
481
482 Raised when trying to run an operation without the adequate access
483 rights - for example filesystem permissions.
484 Corresponds to :c:data:`errno` ``EACCES`` and ``EPERM``.
485
486 .. exception:: ProcessLookupError
487
488 Raised when a given process doesn't exist.
489 Corresponds to :c:data:`errno` ``ESRCH``.
490
491 .. exception:: TimeoutError
492
493 Raised when a system function timed out at the system level.
494 Corresponds to :c:data:`errno` ``ETIMEDOUT``.
495
496 .. versionadded:: 3.3
497 All the above :exc:`OSError` subclasses were added.
498
499
500 .. seealso::
501
502 :pep:`3151` - Reworking the OS and IO exception hierarchy
503 PEP written and implemented by Antoine Pitrou.
504
505
506 Warnings
507 --------
508
404 The following exceptions are used as warning categories; see the :mod:`warnings` 509 The following exceptions are used as warning categories; see the :mod:`warnings`
405 module for more information. 510 module for more information.
406 511
407 .. exception:: Warning 512 .. exception:: Warning
408 513
409 Base class for warning categories. 514 Base class for warning categories.
410 515
411 516
412 .. exception:: UserWarning 517 .. exception:: UserWarning
413 518
(...skipping 48 matching lines...) Expand 10 before | Expand all | Expand 10 after
462 .. versionadded:: 3.2 567 .. versionadded:: 3.2
463 568
464 569
465 570
466 Exception hierarchy 571 Exception hierarchy
467 ------------------- 572 -------------------
468 573
469 The class hierarchy for built-in exceptions is: 574 The class hierarchy for built-in exceptions is:
470 575
471 .. literalinclude:: ../../Lib/test/exception_hierarchy.txt 576 .. literalinclude:: ../../Lib/test/exception_hierarchy.txt
LEFTRIGHT

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+