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.

406 lines
14 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, in ?
  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 ?
  35. ZeroDivisionError: division by zero
  36. >>> 4 + spam*3
  37. Traceback (most recent call last):
  38. File "<stdin>", line 1, in ?
  39. NameError: name 'spam' is not defined
  40. >>> '2' + 2
  41. Traceback (most recent call last):
  42. File "<stdin>", line 1, in ?
  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. The last except clause may omit the exception name(s), to serve as a wildcard.
  94. Use this with extreme caution, since it is easy to mask a real programming error
  95. in this way! It can also be used to print an error message and then re-raise
  96. the exception (allowing a caller to handle the exception as well)::
  97. import sys
  98. try:
  99. f = open('myfile.txt')
  100. s = f.readline()
  101. i = int(s.strip())
  102. except OSError as err:
  103. print("OS error: {0}".format(err))
  104. except ValueError:
  105. print("Could not convert data to an integer.")
  106. except:
  107. print("Unexpected error:", sys.exc_info()[0])
  108. raise
  109. The :keyword:`try` ... :keyword:`except` statement has an optional *else
  110. clause*, which, when present, must follow all except clauses. It is useful for
  111. code that must be executed if the try clause does not raise an exception. For
  112. example::
  113. for arg in sys.argv[1:]:
  114. try:
  115. f = open(arg, 'r')
  116. except IOError:
  117. print('cannot open', arg)
  118. else:
  119. print(arg, 'has', len(f.readlines()), 'lines')
  120. f.close()
  121. The use of the :keyword:`else` clause is better than adding additional code to
  122. the :keyword:`try` clause because it avoids accidentally catching an exception
  123. that wasn't raised by the code being protected by the :keyword:`try` ...
  124. :keyword:`except` statement.
  125. When an exception occurs, it may have an associated value, also known as the
  126. exception's *argument*. The presence and type of the argument depend on the
  127. exception type.
  128. The except clause may specify a variable after the exception name. The
  129. variable is bound to an exception instance with the arguments stored in
  130. ``instance.args``. For convenience, the exception instance defines
  131. :meth:`__str__` so the arguments can be printed directly without having to
  132. reference ``.args``. One may also instantiate an exception first before
  133. raising it and add any attributes to it as desired. ::
  134. >>> try:
  135. ... raise Exception('spam', 'eggs')
  136. ... except Exception as inst:
  137. ... print(type(inst)) # the exception instance
  138. ... print(inst.args) # arguments stored in .args
  139. ... print(inst) # __str__ allows args to be printed directly,
  140. ... # but may be overridden in exception subclasses
  141. ... x, y = inst.args # unpack args
  142. ... print('x =', x)
  143. ... print('y =', y)
  144. ...
  145. <class 'Exception'>
  146. ('spam', 'eggs')
  147. ('spam', 'eggs')
  148. x = spam
  149. y = eggs
  150. If an exception has arguments, they are printed as the last part ('detail') of
  151. the message for unhandled exceptions.
  152. Exception handlers don't just handle exceptions if they occur immediately in the
  153. try clause, but also if they occur inside functions that are called (even
  154. indirectly) in the try clause. For example::
  155. >>> def this_fails():
  156. ... x = 1/0
  157. ...
  158. >>> try:
  159. ... this_fails()
  160. ... except ZeroDivisionError as err:
  161. ... print('Handling run-time error:', err)
  162. ...
  163. Handling run-time error: int division or modulo by zero
  164. .. _tut-raising:
  165. Raising Exceptions
  166. ==================
  167. The :keyword:`raise` statement allows the programmer to force a specified
  168. exception to occur. For example::
  169. >>> raise NameError('HiThere')
  170. Traceback (most recent call last):
  171. File "<stdin>", line 1, in ?
  172. NameError: HiThere
  173. The sole argument to :keyword:`raise` indicates the exception to be raised.
  174. This must be either an exception instance or an exception class (a class that
  175. derives from :class:`Exception`).
  176. If you need to determine whether an exception was raised but don't intend to
  177. handle it, a simpler form of the :keyword:`raise` statement allows you to
  178. re-raise the exception::
  179. >>> try:
  180. ... raise NameError('HiThere')
  181. ... except NameError:
  182. ... print('An exception flew by!')
  183. ... raise
  184. ...
  185. An exception flew by!
  186. Traceback (most recent call last):
  187. File "<stdin>", line 2, in ?
  188. NameError: HiThere
  189. .. _tut-userexceptions:
  190. User-defined Exceptions
  191. =======================
  192. Programs may name their own exceptions by creating a new exception class (see
  193. :ref:`tut-classes` for more about Python classes). Exceptions should typically
  194. be derived from the :exc:`Exception` class, either directly or indirectly. For
  195. example::
  196. >>> class MyError(Exception):
  197. ... def __init__(self, value):
  198. ... self.value = value
  199. ... def __str__(self):
  200. ... return repr(self.value)
  201. ...
  202. >>> try:
  203. ... raise MyError(2*2)
  204. ... except MyError as e:
  205. ... print('My exception occurred, value:', e.value)
  206. ...
  207. My exception occurred, value: 4
  208. >>> raise MyError('oops!')
  209. Traceback (most recent call last):
  210. File "<stdin>", line 1, in ?
  211. __main__.MyError: 'oops!'
  212. In this example, the default :meth:`__init__` of :class:`Exception` has been
  213. overridden. The new behavior simply creates the *value* attribute. This
  214. replaces the default behavior of creating the *args* attribute.
  215. Exception classes can be defined which do anything any other class can do, but
  216. are usually kept simple, often only offering a number of attributes that allow
  217. information about the error to be extracted by handlers for the exception. When
  218. creating a module that can raise several distinct errors, a common practice is
  219. to create a base class for exceptions defined by that module, and subclass that
  220. to create specific exception classes for different error conditions::
  221. class Error(Exception):
  222. """Base class for exceptions in this module."""
  223. pass
  224. class InputError(Error):
  225. """Exception raised for errors in the input.
  226. Attributes:
  227. expression -- input expression in which the error occurred
  228. message -- explanation of the error
  229. """
  230. def __init__(self, expression, message):
  231. self.expression = expression
  232. self.message = message
  233. class TransitionError(Error):
  234. """Raised when an operation attempts a state transition that's not
  235. allowed.
  236. Attributes:
  237. previous -- state at beginning of transition
  238. next -- attempted new state
  239. message -- explanation of why the specific transition is not allowed
  240. """
  241. def __init__(self, previous, next, message):
  242. self.previous = previous
  243. self.next = next
  244. self.message = message
  245. Most exceptions are defined with names that end in "Error," similar to the
  246. naming of the standard exceptions.
  247. Many standard modules define their own exceptions to report errors that may
  248. occur in functions they define. More information on classes is presented in
  249. chapter :ref:`tut-classes`.
  250. .. _tut-cleanup:
  251. Defining Clean-up Actions
  252. =========================
  253. The :keyword:`try` statement has another optional clause which is intended to
  254. define clean-up actions that must be executed under all circumstances. For
  255. example::
  256. >>> try:
  257. ... raise KeyboardInterrupt
  258. ... finally:
  259. ... print('Goodbye, world!')
  260. ...
  261. Goodbye, world!
  262. Traceback (most recent call last):
  263. File "<stdin>", line 2, in ?
  264. KeyboardInterrupt
  265. A *finally clause* is always executed before leaving the :keyword:`try`
  266. statement, whether an exception has occurred or not. When an exception has
  267. occurred in the :keyword:`try` clause and has not been handled by an
  268. :keyword:`except` clause (or it has occurred in a :keyword:`except` or
  269. :keyword:`else` clause), it is re-raised after the :keyword:`finally` clause has
  270. been executed. The :keyword:`finally` clause is also executed "on the way out"
  271. when any other clause of the :keyword:`try` statement is left via a
  272. :keyword:`break`, :keyword:`continue` or :keyword:`return` statement. A more
  273. complicated example::
  274. >>> def divide(x, y):
  275. ... try:
  276. ... result = x / y
  277. ... except ZeroDivisionError:
  278. ... print("division by zero!")
  279. ... else:
  280. ... print("result is", result)
  281. ... finally:
  282. ... print("executing finally clause")
  283. ...
  284. >>> divide(2, 1)
  285. result is 2.0
  286. executing finally clause
  287. >>> divide(2, 0)
  288. division by zero!
  289. executing finally clause
  290. >>> divide("2", "1")
  291. executing finally clause
  292. Traceback (most recent call last):
  293. File "<stdin>", line 1, in ?
  294. File "<stdin>", line 3, in divide
  295. TypeError: unsupported operand type(s) for /: 'str' and 'str'
  296. As you can see, the :keyword:`finally` clause is executed in any event. The
  297. :exc:`TypeError` raised by dividing two strings is not handled by the
  298. :keyword:`except` clause and therefore re-raised after the :keyword:`finally`
  299. clause has been executed.
  300. In real world applications, the :keyword:`finally` clause is useful for
  301. releasing external resources (such as files or network connections), regardless
  302. of whether the use of the resource was successful.
  303. .. _tut-cleanup-with:
  304. Predefined Clean-up Actions
  305. ===========================
  306. Some objects define standard clean-up actions to be undertaken when the object
  307. is no longer needed, regardless of whether or not the operation using the object
  308. succeeded or failed. Look at the following example, which tries to open a file
  309. and print its contents to the screen. ::
  310. for line in open("myfile.txt"):
  311. print(line, end="")
  312. The problem with this code is that it leaves the file open for an indeterminate
  313. amount of time after this part of the code has finished executing.
  314. This is not an issue in simple scripts, but can be a problem for larger
  315. applications. The :keyword:`with` statement allows objects like files to be
  316. used in a way that ensures they are always cleaned up promptly and correctly. ::
  317. with open("myfile.txt") as f:
  318. for line in f:
  319. print(line, end="")
  320. After the statement is executed, the file *f* is always closed, even if a
  321. problem was encountered while processing the lines. Objects which, like files,
  322. provide predefined clean-up actions will indicate this in their documentation.