You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

414 lines
15 KiB

Merged revisions 66457-66459,66465-66468,66483-66485,66487-66491 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r66457 | antoine.pitrou | 2008-09-13 15:30:30 -0500 (Sat, 13 Sep 2008) | 5 lines Issue #3850: Misc/find_recursionlimit.py was broken. Reviewed by A.M. Kuchling. ........ r66458 | benjamin.peterson | 2008-09-13 17:54:43 -0500 (Sat, 13 Sep 2008) | 1 line fix a name issue; note all doc files should be encoded in utf8 ........ r66459 | benjamin.peterson | 2008-09-14 11:02:22 -0500 (Sun, 14 Sep 2008) | 1 line clarify that radix for int is not 'guessed' ........ r66465 | skip.montanaro | 2008-09-14 21:03:05 -0500 (Sun, 14 Sep 2008) | 3 lines Review usage. Fix a mistake in the new-style class definition. Add a couple new definitions (CPython and virtual machine). ........ r66466 | skip.montanaro | 2008-09-14 21:19:53 -0500 (Sun, 14 Sep 2008) | 2 lines Pick up a few more definitions from the glossary on the wiki. ........ r66467 | benjamin.peterson | 2008-09-14 21:53:23 -0500 (Sun, 14 Sep 2008) | 1 line mention that object.__init__ no longer takes arbitrary args and kwargs ........ r66468 | andrew.kuchling | 2008-09-15 08:08:32 -0500 (Mon, 15 Sep 2008) | 1 line Rewrite item a bit ........ r66483 | georg.brandl | 2008-09-16 05:17:45 -0500 (Tue, 16 Sep 2008) | 2 lines Fix typo. ........ r66484 | benjamin.peterson | 2008-09-16 16:20:28 -0500 (Tue, 16 Sep 2008) | 2 lines be less wordy ........ r66485 | georg.brandl | 2008-09-17 03:45:54 -0500 (Wed, 17 Sep 2008) | 2 lines #3888: add some deprecated modules in whatsnew. ........ r66487 | skip.montanaro | 2008-09-17 06:50:36 -0500 (Wed, 17 Sep 2008) | 2 lines usage ........ r66488 | andrew.kuchling | 2008-09-17 07:57:04 -0500 (Wed, 17 Sep 2008) | 1 line Markup fixes ........ r66489 | andrew.kuchling | 2008-09-17 07:58:22 -0500 (Wed, 17 Sep 2008) | 2 lines Remove comment about improvement: pystone is about the same, and the improvements seem to be difficult to quantify ........ r66490 | andrew.kuchling | 2008-09-17 08:04:53 -0500 (Wed, 17 Sep 2008) | 1 line Note sqlite3 version; move item ........ r66491 | benjamin.peterson | 2008-09-17 16:54:56 -0500 (Wed, 17 Sep 2008) | 1 line document compileall command flags ........
18 years ago
  1. .. _tut-errors:
  2. *********************
  3. Errors and Exceptions
  4. *********************
  5. Until now error messages haven't been more than mentioned, but if you have tried
  6. out the examples you have probably seen some. There are (at least) two
  7. distinguishable kinds of errors: *syntax errors* and *exceptions*.
  8. .. _tut-syntaxerrors:
  9. Syntax Errors
  10. =============
  11. Syntax errors, also known as parsing errors, are perhaps the most common kind of
  12. complaint you get while you are still learning Python::
  13. >>> while True print('Hello world')
  14. File "<stdin>", line 1
  15. while True print('Hello world')
  16. ^
  17. SyntaxError: invalid syntax
  18. The parser repeats the offending line and displays a little 'arrow' pointing at
  19. the earliest point in the line where the error was detected. The error is
  20. caused by (or at least detected at) the token *preceding* the arrow: in the
  21. example, the error is detected at the function :func:`print`, since a colon
  22. (``':'``) is missing before it. File name and line number are printed so you
  23. know where to look in case the input came from a script.
  24. .. _tut-exceptions:
  25. Exceptions
  26. ==========
  27. Even if a statement or expression is syntactically correct, it may cause an
  28. error when an attempt is made to execute it. Errors detected during execution
  29. are called *exceptions* and are not unconditionally fatal: you will soon learn
  30. how to handle them in Python programs. Most exceptions are not handled by
  31. programs, however, and result in error messages as shown here::
  32. >>> 10 * (1/0)
  33. Traceback (most recent call last):
  34. File "<stdin>", line 1, in <module>
  35. ZeroDivisionError: division by zero
  36. >>> 4 + spam*3
  37. Traceback (most recent call last):
  38. File "<stdin>", line 1, in <module>
  39. NameError: name 'spam' is not defined
  40. >>> '2' + 2
  41. Traceback (most recent call last):
  42. File "<stdin>", line 1, in <module>
  43. TypeError: Can't convert 'int' object to str implicitly
  44. The last line of the error message indicates what happened. Exceptions come in
  45. different types, and the type is printed as part of the message: the types in
  46. the example are :exc:`ZeroDivisionError`, :exc:`NameError` and :exc:`TypeError`.
  47. The string printed as the exception type is the name of the built-in exception
  48. that occurred. This is true for all built-in exceptions, but need not be true
  49. for user-defined exceptions (although it is a useful convention). Standard
  50. exception names are built-in identifiers (not reserved keywords).
  51. The rest of the line provides detail based on the type of exception and what
  52. caused it.
  53. The preceding part of the error message shows the context where the exception
  54. happened, in the form of a stack traceback. In general it contains a stack
  55. traceback listing source lines; however, it will not display lines read from
  56. standard input.
  57. :ref:`bltin-exceptions` lists the built-in exceptions and their meanings.
  58. .. _tut-handling:
  59. Handling Exceptions
  60. ===================
  61. It is possible to write programs that handle selected exceptions. Look at the
  62. following example, which asks the user for input until a valid integer has been
  63. entered, but allows the user to interrupt the program (using :kbd:`Control-C` or
  64. whatever the operating system supports); note that a user-generated interruption
  65. is signalled by raising the :exc:`KeyboardInterrupt` exception. ::
  66. >>> while True:
  67. ... try:
  68. ... x = int(input("Please enter a number: "))
  69. ... break
  70. ... except ValueError:
  71. ... print("Oops! That was no valid number. Try again...")
  72. ...
  73. The :keyword:`try` statement works as follows.
  74. * First, the *try clause* (the statement(s) between the :keyword:`try` and
  75. :keyword:`except` keywords) is executed.
  76. * If no exception occurs, the *except clause* is skipped and execution of the
  77. :keyword:`try` statement is finished.
  78. * If an exception occurs during execution of the try clause, the rest of the
  79. clause is skipped. Then if its type matches the exception named after the
  80. :keyword:`except` keyword, the except clause is executed, and then execution
  81. continues after the :keyword:`try` statement.
  82. * If an exception occurs which does not match the exception named in the except
  83. clause, it is passed on to outer :keyword:`try` statements; if no handler is
  84. found, it is an *unhandled exception* and execution stops with a message as
  85. shown above.
  86. A :keyword:`try` statement may have more than one except clause, to specify
  87. handlers for different exceptions. At most one handler will be executed.
  88. Handlers only handle exceptions that occur in the corresponding try clause, not
  89. in other handlers of the same :keyword:`try` statement. An except clause may
  90. name multiple exceptions as a parenthesized tuple, for example::
  91. ... except (RuntimeError, TypeError, NameError):
  92. ... pass
  93. A class in an :keyword:`except` clause is compatible with an exception if it is
  94. the same class or a base class thereof (but not the other way around --- an
  95. except clause listing a derived class is not compatible with a base class). For
  96. example, the following code will print B, C, D in that order::
  97. class B(Exception):
  98. pass
  99. class C(B):
  100. pass
  101. class D(C):
  102. pass
  103. for cls in [B, C, D]:
  104. try:
  105. raise cls()
  106. except D:
  107. print("D")
  108. except C:
  109. print("C")
  110. except B:
  111. print("B")
  112. Note that if the except clauses were reversed (with ``except B`` first), it
  113. would have printed B, B, B --- the first matching except clause is triggered.
  114. The last except clause may omit the exception name(s), to serve as a wildcard.
  115. Use this with extreme caution, since it is easy to mask a real programming error
  116. in this way! It can also be used to print an error message and then re-raise
  117. the exception (allowing a caller to handle the exception as well)::
  118. import sys
  119. try:
  120. f = open('myfile.txt')
  121. s = f.readline()
  122. i = int(s.strip())
  123. except OSError as err:
  124. print("OS error: {0}".format(err))
  125. except ValueError:
  126. print("Could not convert data to an integer.")
  127. except:
  128. print("Unexpected error:", sys.exc_info()[0])
  129. raise
  130. The :keyword:`try` ... :keyword:`except` statement has an optional *else
  131. clause*, which, when present, must follow all except clauses. It is useful for
  132. code that must be executed if the try clause does not raise an exception. For
  133. example::
  134. for arg in sys.argv[1:]:
  135. try:
  136. f = open(arg, 'r')
  137. except OSError:
  138. print('cannot open', arg)
  139. else:
  140. print(arg, 'has', len(f.readlines()), 'lines')
  141. f.close()
  142. The use of the :keyword:`else` clause is better than adding additional code to
  143. the :keyword:`try` clause because it avoids accidentally catching an exception
  144. that wasn't raised by the code being protected by the :keyword:`try` ...
  145. :keyword:`except` statement.
  146. When an exception occurs, it may have an associated value, also known as the
  147. exception's *argument*. The presence and type of the argument depend on the
  148. exception type.
  149. The except clause may specify a variable after the exception name. The
  150. variable is bound to an exception instance with the arguments stored in
  151. ``instance.args``. For convenience, the exception instance defines
  152. :meth:`__str__` so the arguments can be printed directly without having to
  153. reference ``.args``. One may also instantiate an exception first before
  154. raising it and add any attributes to it as desired. ::
  155. >>> try:
  156. ... raise Exception('spam', 'eggs')
  157. ... except Exception as inst:
  158. ... print(type(inst)) # the exception instance
  159. ... print(inst.args) # arguments stored in .args
  160. ... print(inst) # __str__ allows args to be printed directly,
  161. ... # but may be overridden in exception subclasses
  162. ... x, y = inst.args # unpack args
  163. ... print('x =', x)
  164. ... print('y =', y)
  165. ...
  166. <class 'Exception'>
  167. ('spam', 'eggs')
  168. ('spam', 'eggs')
  169. x = spam
  170. y = eggs
  171. If an exception has arguments, they are printed as the last part ('detail') of
  172. the message for unhandled exceptions.
  173. Exception handlers don't just handle exceptions if they occur immediately in the
  174. try clause, but also if they occur inside functions that are called (even
  175. indirectly) in the try clause. For example::
  176. >>> def this_fails():
  177. ... x = 1/0
  178. ...
  179. >>> try:
  180. ... this_fails()
  181. ... except ZeroDivisionError as err:
  182. ... print('Handling run-time error:', err)
  183. ...
  184. Handling run-time error: division by zero
  185. .. _tut-raising:
  186. Raising Exceptions
  187. ==================
  188. The :keyword:`raise` statement allows the programmer to force a specified
  189. exception to occur. For example::
  190. >>> raise NameError('HiThere')
  191. Traceback (most recent call last):
  192. File "<stdin>", line 1, in <module>
  193. NameError: HiThere
  194. The sole argument to :keyword:`raise` indicates the exception to be raised.
  195. This must be either an exception instance or an exception class (a class that
  196. derives from :class:`Exception`). If an exception class is passed, it will
  197. be implicitly instantiated by calling its constructor with no arguments::
  198. raise ValueError # shorthand for 'raise ValueError()'
  199. If you need to determine whether an exception was raised but don't intend to
  200. handle it, a simpler form of the :keyword:`raise` statement allows you to
  201. re-raise the exception::
  202. >>> try:
  203. ... raise NameError('HiThere')
  204. ... except NameError:
  205. ... print('An exception flew by!')
  206. ... raise
  207. ...
  208. An exception flew by!
  209. Traceback (most recent call last):
  210. File "<stdin>", line 2, in <module>
  211. NameError: HiThere
  212. .. _tut-userexceptions:
  213. User-defined Exceptions
  214. =======================
  215. Programs may name their own exceptions by creating a new exception class (see
  216. :ref:`tut-classes` for more about Python classes). Exceptions should typically
  217. be derived from the :exc:`Exception` class, either directly or indirectly.
  218. Exception classes can be defined which do anything any other class can do, but
  219. are usually kept simple, often only offering a number of attributes that allow
  220. information about the error to be extracted by handlers for the exception. When
  221. creating a module that can raise several distinct errors, a common practice is
  222. to create a base class for exceptions defined by that module, and subclass that
  223. to create specific exception classes for different error conditions::
  224. class Error(Exception):
  225. """Base class for exceptions in this module."""
  226. pass
  227. class InputError(Error):
  228. """Exception raised for errors in the input.
  229. Attributes:
  230. expression -- input expression in which the error occurred
  231. message -- explanation of the error
  232. """
  233. def __init__(self, expression, message):
  234. self.expression = expression
  235. self.message = message
  236. class TransitionError(Error):
  237. """Raised when an operation attempts a state transition that's not
  238. allowed.
  239. Attributes:
  240. previous -- state at beginning of transition
  241. next -- attempted new state
  242. message -- explanation of why the specific transition is not allowed
  243. """
  244. def __init__(self, previous, next, message):
  245. self.previous = previous
  246. self.next = next
  247. self.message = message
  248. Most exceptions are defined with names that end in "Error," similar to the
  249. naming of the standard exceptions.
  250. Many standard modules define their own exceptions to report errors that may
  251. occur in functions they define. More information on classes is presented in
  252. chapter :ref:`tut-classes`.
  253. .. _tut-cleanup:
  254. Defining Clean-up Actions
  255. =========================
  256. The :keyword:`try` statement has another optional clause which is intended to
  257. define clean-up actions that must be executed under all circumstances. For
  258. example::
  259. >>> try:
  260. ... raise KeyboardInterrupt
  261. ... finally:
  262. ... print('Goodbye, world!')
  263. ...
  264. Goodbye, world!
  265. Traceback (most recent call last):
  266. File "<stdin>", line 2, in <module>
  267. KeyboardInterrupt
  268. A *finally clause* is always executed before leaving the :keyword:`try`
  269. statement, whether an exception has occurred or not. When an exception has
  270. occurred in the :keyword:`try` clause and has not been handled by an
  271. :keyword:`except` clause (or it has occurred in an :keyword:`except` or
  272. :keyword:`else` clause), it is re-raised after the :keyword:`finally` clause has
  273. been executed. The :keyword:`finally` clause is also executed "on the way out"
  274. when any other clause of the :keyword:`try` statement is left via a
  275. :keyword:`break`, :keyword:`continue` or :keyword:`return` statement. A more
  276. complicated example::
  277. >>> def divide(x, y):
  278. ... try:
  279. ... result = x / y
  280. ... except ZeroDivisionError:
  281. ... print("division by zero!")
  282. ... else:
  283. ... print("result is", result)
  284. ... finally:
  285. ... print("executing finally clause")
  286. ...
  287. >>> divide(2, 1)
  288. result is 2.0
  289. executing finally clause
  290. >>> divide(2, 0)
  291. division by zero!
  292. executing finally clause
  293. >>> divide("2", "1")
  294. executing finally clause
  295. Traceback (most recent call last):
  296. File "<stdin>", line 1, in <module>
  297. File "<stdin>", line 3, in divide
  298. TypeError: unsupported operand type(s) for /: 'str' and 'str'
  299. As you can see, the :keyword:`finally` clause is executed in any event. The
  300. :exc:`TypeError` raised by dividing two strings is not handled by the
  301. :keyword:`except` clause and therefore re-raised after the :keyword:`finally`
  302. clause has been executed.
  303. In real world applications, the :keyword:`finally` clause is useful for
  304. releasing external resources (such as files or network connections), regardless
  305. of whether the use of the resource was successful.
  306. .. _tut-cleanup-with:
  307. Predefined Clean-up Actions
  308. ===========================
  309. Some objects define standard clean-up actions to be undertaken when the object
  310. is no longer needed, regardless of whether or not the operation using the object
  311. succeeded or failed. Look at the following example, which tries to open a file
  312. and print its contents to the screen. ::
  313. for line in open("myfile.txt"):
  314. print(line, end="")
  315. The problem with this code is that it leaves the file open for an indeterminate
  316. amount of time after this part of the code has finished executing.
  317. This is not an issue in simple scripts, but can be a problem for larger
  318. applications. The :keyword:`with` statement allows objects like files to be
  319. used in a way that ensures they are always cleaned up promptly and correctly. ::
  320. with open("myfile.txt") as f:
  321. for line in f:
  322. print(line, end="")
  323. After the statement is executed, the file *f* is always closed, even if a
  324. problem was encountered while processing the lines. Objects which, like files,
  325. provide predefined clean-up actions will indicate this in their documentation.