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.

416 lines
15 KiB

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