/Doc/library/exceptions.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 486 lines · 298 code · 188 blank · 0 comment · 0 complexity · d51580f3bd34d0ec2dd8ca951564dd9b MD5 · raw file

  1. .. _bltin-exceptions:
  2. Built-in Exceptions
  3. ===================
  4. .. module:: exceptions
  5. :synopsis: Standard exception classes.
  6. Exceptions should be class objects. The exceptions are defined in the module
  7. :mod:`exceptions`. This module never needs to be imported explicitly: the
  8. exceptions are provided in the built-in namespace as well as the
  9. :mod:`exceptions` module.
  10. .. index::
  11. statement: try
  12. statement: except
  13. For class exceptions, in a :keyword:`try` statement with an :keyword:`except`
  14. clause that mentions a particular class, that clause also handles any exception
  15. classes derived from that class (but not exception classes from which *it* is
  16. derived). Two exception classes that are not related via subclassing are never
  17. equivalent, even if they have the same name.
  18. .. index:: statement: raise
  19. The built-in exceptions listed below can be generated by the interpreter or
  20. built-in functions. Except where mentioned, they have an "associated value"
  21. indicating the detailed cause of the error. This may be a string or a tuple
  22. containing several items of information (e.g., an error code and a string
  23. explaining the code). The associated value is the second argument to the
  24. :keyword:`raise` statement. If the exception class is derived from the standard
  25. root class :exc:`BaseException`, the associated value is present as the
  26. exception instance's :attr:`args` attribute.
  27. User code can raise built-in exceptions. This can be used to test an exception
  28. handler or to report an error condition "just like" the situation in which the
  29. interpreter raises the same exception; but beware that there is nothing to
  30. prevent user code from raising an inappropriate error.
  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
  33. :exc:`Exception` class and not :exc:`BaseException`. More information on
  34. defining exceptions is available in the Python Tutorial under
  35. :ref:`tut-userexceptions`.
  36. The following exceptions are only used as base classes for other exceptions.
  37. .. exception:: BaseException
  38. The base class for all built-in exceptions. It is not meant to be directly
  39. inherited by user-defined classes (for that use :exc:`Exception`). If
  40. :func:`str` or :func:`unicode` is called on an instance of this class, the
  41. representation of the argument(s) to the instance are returned or the empty
  42. string when there were no arguments. All arguments are stored in :attr:`args`
  43. as a tuple.
  44. .. versionadded:: 2.5
  45. .. exception:: Exception
  46. All built-in, non-system-exiting exceptions are derived from this class. All
  47. user-defined exceptions should also be derived from this class.
  48. .. versionchanged:: 2.5
  49. Changed to inherit from :exc:`BaseException`.
  50. .. exception:: StandardError
  51. The base class for all built-in exceptions except :exc:`StopIteration`,
  52. :exc:`GeneratorExit`, :exc:`KeyboardInterrupt` and :exc:`SystemExit`.
  53. :exc:`StandardError` itself is derived from :exc:`Exception`.
  54. .. exception:: ArithmeticError
  55. The base class for those built-in exceptions that are raised for various
  56. arithmetic errors: :exc:`OverflowError`, :exc:`ZeroDivisionError`,
  57. :exc:`FloatingPointError`.
  58. .. exception:: LookupError
  59. The base class for the exceptions that are raised when a key or index used on a
  60. mapping or sequence is invalid: :exc:`IndexError`, :exc:`KeyError`. This can be
  61. raised directly by :func:`sys.setdefaultencoding`.
  62. .. exception:: EnvironmentError
  63. The base class for exceptions that can occur outside the Python system:
  64. :exc:`IOError`, :exc:`OSError`. When exceptions of this type are created with a
  65. 2-tuple, the first item is available on the instance's :attr:`errno` attribute
  66. (it is assumed to be an error number), and the second item is available on the
  67. :attr:`strerror` attribute (it is usually the associated error message). The
  68. tuple itself is also available on the :attr:`args` attribute.
  69. .. versionadded:: 1.5.2
  70. When an :exc:`EnvironmentError` exception is instantiated with a 3-tuple, the
  71. first two items are available as above, while the third item is available on the
  72. :attr:`filename` attribute. However, for backwards compatibility, the
  73. :attr:`args` attribute contains only a 2-tuple of the first two constructor
  74. arguments.
  75. The :attr:`filename` attribute is ``None`` when this exception is created with
  76. other than 3 arguments. The :attr:`errno` and :attr:`strerror` attributes are
  77. also ``None`` when the instance was created with other than 2 or 3 arguments.
  78. In this last case, :attr:`args` contains the verbatim constructor arguments as a
  79. tuple.
  80. The following exceptions are the exceptions that are actually raised.
  81. .. exception:: AssertionError
  82. .. index:: statement: assert
  83. Raised when an :keyword:`assert` statement fails.
  84. .. exception:: AttributeError
  85. Raised when an attribute reference (see :ref:`attribute-references`) or
  86. assignment fails. (When an object does not support attribute references or
  87. attribute assignments at all, :exc:`TypeError` is raised.)
  88. .. exception:: EOFError
  89. Raised when one of the built-in functions (:func:`input` or :func:`raw_input`)
  90. hits an end-of-file condition (EOF) without reading any data. (N.B.: the
  91. :meth:`file.read` and :meth:`file.readline` methods return an empty string
  92. when they hit EOF.)
  93. .. exception:: FloatingPointError
  94. Raised when a floating point operation fails. This exception is always defined,
  95. but can only be raised when Python is configured with the
  96. :option:`--with-fpectl` option, or the :const:`WANT_SIGFPE_HANDLER` symbol is
  97. defined in the :file:`pyconfig.h` file.
  98. .. exception:: GeneratorExit
  99. Raise when a :term:`generator`\'s :meth:`close` method is called. It
  100. directly inherits from :exc:`BaseException` instead of :exc:`StandardError` since
  101. it is technically not an error.
  102. .. versionadded:: 2.5
  103. .. versionchanged:: 2.6
  104. Changed to inherit from :exc:`BaseException`.
  105. .. exception:: IOError
  106. Raised when an I/O operation (such as a :keyword:`print` statement, the built-in
  107. :func:`open` function or a method of a file object) fails for an I/O-related
  108. reason, e.g., "file not found" or "disk full".
  109. This class is derived from :exc:`EnvironmentError`. See the discussion above
  110. for more information on exception instance attributes.
  111. .. versionchanged:: 2.6
  112. Changed :exc:`socket.error` to use this as a base class.
  113. .. exception:: ImportError
  114. Raised when an :keyword:`import` statement fails to find the module definition
  115. or when a ``from ... import`` fails to find a name that is to be imported.
  116. .. exception:: IndexError
  117. Raised when a sequence subscript is out of range. (Slice indices are silently
  118. truncated to fall in the allowed range; if an index is not a plain integer,
  119. :exc:`TypeError` is raised.)
  120. .. XXX xref to sequences
  121. .. exception:: KeyError
  122. Raised when a mapping (dictionary) key is not found in the set of existing keys.
  123. .. XXX xref to mapping objects?
  124. .. exception:: KeyboardInterrupt
  125. Raised when the user hits the interrupt key (normally :kbd:`Control-C` or
  126. :kbd:`Delete`). During execution, a check for interrupts is made regularly.
  127. Interrupts typed when a built-in function :func:`input` or :func:`raw_input` is
  128. waiting for input also raise this exception. The exception inherits from
  129. :exc:`BaseException` so as to not be accidentally caught by code that catches
  130. :exc:`Exception` and thus prevent the interpreter from exiting.
  131. .. versionchanged:: 2.5
  132. Changed to inherit from :exc:`BaseException`.
  133. .. exception:: MemoryError
  134. Raised when an operation runs out of memory but the situation may still be
  135. rescued (by deleting some objects). The associated value is a string indicating
  136. what kind of (internal) operation ran out of memory. Note that because of the
  137. underlying memory management architecture (C's :cfunc:`malloc` function), the
  138. interpreter may not always be able to completely recover from this situation; it
  139. nevertheless raises an exception so that a stack traceback can be printed, in
  140. case a run-away program was the cause.
  141. .. exception:: NameError
  142. Raised when a local or global name is not found. This applies only to
  143. unqualified names. The associated value is an error message that includes the
  144. name that could not be found.
  145. .. exception:: NotImplementedError
  146. This exception is derived from :exc:`RuntimeError`. In user defined base
  147. classes, abstract methods should raise this exception when they require derived
  148. classes to override the method.
  149. .. versionadded:: 1.5.2
  150. .. exception:: OSError
  151. .. index:: module: errno
  152. This exception is derived from :exc:`EnvironmentError`. It is raised when a
  153. function returns a system-related error (not for illegal argument types or
  154. other incidental errors). The :attr:`errno` attribute is a numeric error
  155. code from :cdata:`errno`, and the :attr:`strerror` attribute is the
  156. corresponding string, as would be printed by the C function :cfunc:`perror`.
  157. See the module :mod:`errno`, which contains names for the error codes defined
  158. by the underlying operating system.
  159. For exceptions that involve a file system path (such as :func:`chdir` or
  160. :func:`unlink`), the exception instance will contain a third attribute,
  161. :attr:`filename`, which is the file name passed to the function.
  162. .. versionadded:: 1.5.2
  163. .. exception:: OverflowError
  164. Raised when the result of an arithmetic operation is too large to be
  165. represented. This cannot occur for long integers (which would rather raise
  166. :exc:`MemoryError` than give up) and for most operations with plain integers,
  167. which return a long integer instead. Because of the lack of standardization
  168. of floating point exception handling in C, most floating point operations
  169. also aren't checked.
  170. .. exception:: ReferenceError
  171. This exception is raised when a weak reference proxy, created by the
  172. :func:`weakref.proxy` function, is used to access an attribute of the referent
  173. after it has been garbage collected. For more information on weak references,
  174. see the :mod:`weakref` module.
  175. .. versionadded:: 2.2
  176. Previously known as the :exc:`weakref.ReferenceError` exception.
  177. .. exception:: RuntimeError
  178. Raised when an error is detected that doesn't fall in any of the other
  179. categories. The associated value is a string indicating what precisely went
  180. wrong. (This exception is mostly a relic from a previous version of the
  181. interpreter; it is not used very much any more.)
  182. .. exception:: StopIteration
  183. Raised by an :term:`iterator`\'s :meth:`next` method to signal that there are
  184. no further values. This is derived from :exc:`Exception` rather than
  185. :exc:`StandardError`, since this is not considered an error in its normal
  186. application.
  187. .. versionadded:: 2.2
  188. .. exception:: SyntaxError
  189. Raised when the parser encounters a syntax error. This may occur in an
  190. :keyword:`import` statement, in an :keyword:`exec` statement, in a call to the
  191. built-in function :func:`eval` or :func:`input`, or when reading the initial
  192. script or standard input (also interactively).
  193. Instances of this class have attributes :attr:`filename`, :attr:`lineno`,
  194. :attr:`offset` and :attr:`text` for easier access to the details. :func:`str`
  195. of the exception instance returns only the message.
  196. .. exception:: SystemError
  197. Raised when the interpreter finds an internal error, but the situation does not
  198. look so serious to cause it to abandon all hope. The associated value is a
  199. string indicating what went wrong (in low-level terms).
  200. You should report this to the author or maintainer of your Python interpreter.
  201. Be sure to report the version of the Python interpreter (``sys.version``; it is
  202. also printed at the start of an interactive Python session), the exact error
  203. message (the exception's associated value) and if possible the source of the
  204. program that triggered the error.
  205. .. exception:: SystemExit
  206. This exception is raised by the :func:`sys.exit` function. When it is not
  207. handled, the Python interpreter exits; no stack traceback is printed. If the
  208. associated value is a plain integer, it specifies the system exit status (passed
  209. to C's :cfunc:`exit` function); if it is ``None``, the exit status is zero; if
  210. it has another type (such as a string), the object's value is printed and the
  211. exit status is one.
  212. Instances have an attribute :attr:`code` which is set to the proposed exit
  213. status or error message (defaulting to ``None``). Also, this exception derives
  214. directly from :exc:`BaseException` and not :exc:`StandardError`, since it is not
  215. technically an error.
  216. A call to :func:`sys.exit` is translated into an exception so that clean-up
  217. handlers (:keyword:`finally` clauses of :keyword:`try` statements) can be
  218. executed, and so that a debugger can execute a script without running the risk
  219. of losing control. The :func:`os._exit` function can be used if it is
  220. absolutely positively necessary to exit immediately (for example, in the child
  221. process after a call to :func:`fork`).
  222. The exception inherits from :exc:`BaseException` instead of :exc:`StandardError`
  223. or :exc:`Exception` so that it is not accidentally caught by code that catches
  224. :exc:`Exception`. This allows the exception to properly propagate up and cause
  225. the interpreter to exit.
  226. .. versionchanged:: 2.5
  227. Changed to inherit from :exc:`BaseException`.
  228. .. exception:: TypeError
  229. Raised when an operation or function is applied to an object of inappropriate
  230. type. The associated value is a string giving details about the type mismatch.
  231. .. exception:: UnboundLocalError
  232. Raised when a reference is made to a local variable in a function or method, but
  233. no value has been bound to that variable. This is a subclass of
  234. :exc:`NameError`.
  235. .. versionadded:: 2.0
  236. .. exception:: UnicodeError
  237. Raised when a Unicode-related encoding or decoding error occurs. It is a
  238. subclass of :exc:`ValueError`.
  239. .. versionadded:: 2.0
  240. .. exception:: UnicodeEncodeError
  241. Raised when a Unicode-related error occurs during encoding. It is a subclass of
  242. :exc:`UnicodeError`.
  243. .. versionadded:: 2.3
  244. .. exception:: UnicodeDecodeError
  245. Raised when a Unicode-related error occurs during decoding. It is a subclass of
  246. :exc:`UnicodeError`.
  247. .. versionadded:: 2.3
  248. .. exception:: UnicodeTranslateError
  249. Raised when a Unicode-related error occurs during translating. It is a subclass
  250. of :exc:`UnicodeError`.
  251. .. versionadded:: 2.3
  252. .. exception:: ValueError
  253. Raised when a built-in operation or function receives an argument that has the
  254. right type but an inappropriate value, and the situation is not described by a
  255. more precise exception such as :exc:`IndexError`.
  256. .. exception:: VMSError
  257. Only available on VMS. Raised when a VMS-specific error occurs.
  258. .. exception:: WindowsError
  259. Raised when a Windows-specific error occurs or when the error number does not
  260. correspond to an :cdata:`errno` value. The :attr:`winerror` and
  261. :attr:`strerror` values are created from the return values of the
  262. :cfunc:`GetLastError` and :cfunc:`FormatMessage` functions from the Windows
  263. Platform API. The :attr:`errno` value maps the :attr:`winerror` value to
  264. corresponding ``errno.h`` values. This is a subclass of :exc:`OSError`.
  265. .. versionadded:: 2.0
  266. .. versionchanged:: 2.5
  267. Previous versions put the :cfunc:`GetLastError` codes into :attr:`errno`.
  268. .. exception:: ZeroDivisionError
  269. Raised when the second argument of a division or modulo operation is zero. The
  270. associated value is a string indicating the type of the operands and the
  271. operation.
  272. The following exceptions are used as warning categories; see the :mod:`warnings`
  273. module for more information.
  274. .. exception:: Warning
  275. Base class for warning categories.
  276. .. exception:: UserWarning
  277. Base class for warnings generated by user code.
  278. .. exception:: DeprecationWarning
  279. Base class for warnings about deprecated features.
  280. .. exception:: PendingDeprecationWarning
  281. Base class for warnings about features which will be deprecated in the future.
  282. .. exception:: SyntaxWarning
  283. Base class for warnings about dubious syntax
  284. .. exception:: RuntimeWarning
  285. Base class for warnings about dubious runtime behavior.
  286. .. exception:: FutureWarning
  287. Base class for warnings about constructs that will change semantically in the
  288. future.
  289. .. exception:: ImportWarning
  290. Base class for warnings about probable mistakes in module imports.
  291. .. versionadded:: 2.5
  292. .. exception:: UnicodeWarning
  293. Base class for warnings related to Unicode.
  294. .. versionadded:: 2.5
  295. Exception hierarchy
  296. -------------------
  297. The class hierarchy for built-in exceptions is:
  298. .. literalinclude:: ../../Lib/test/exception_hierarchy.txt