/Doc/tutorial/errors.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 410 lines · 325 code · 85 blank · 0 comment · 0 complexity · 4f1bcd59c8dab80f0fd03ac934d2383e MD5 · raw file

  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. 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 IOError as (errno, strerror):
  103. print "I/O error({0}): {1}".format(errno, strerror)
  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 (or tuple).
  129. The variable is bound to an exception instance with the arguments stored in
  130. ``instance.args``. For convenience, the exception instance defines
  131. :meth:`__getitem__` and :meth:`__str__` so the arguments can be accessed or
  132. printed directly without having to reference ``.args``.
  133. But use of ``.args`` is discouraged. Instead, the preferred use is to pass a
  134. single argument to an exception (which can be a tuple if multiple arguments are
  135. needed) and have it bound to the ``message`` attribute. One may also
  136. instantiate an exception first before raising it and add any attributes to it as
  137. desired. ::
  138. >>> try:
  139. ... raise Exception('spam', 'eggs')
  140. ... except Exception as inst:
  141. ... print type(inst) # the exception instance
  142. ... print inst.args # arguments stored in .args
  143. ... print inst # __str__ allows args to printed directly
  144. ... x, y = inst # __getitem__ allows args to be unpacked directly
  145. ... print 'x =', x
  146. ... print 'y =', y
  147. ...
  148. <type 'exceptions.Exception'>
  149. ('spam', 'eggs')
  150. ('spam', 'eggs')
  151. x = spam
  152. y = eggs
  153. If an exception has an argument, it is printed as the last part ('detail') of
  154. the message for unhandled exceptions.
  155. Exception handlers don't just handle exceptions if they occur immediately in the
  156. try clause, but also if they occur inside functions that are called (even
  157. indirectly) in the try clause. For example::
  158. >>> def this_fails():
  159. ... x = 1/0
  160. ...
  161. >>> try:
  162. ... this_fails()
  163. ... except ZeroDivisionError as detail:
  164. ... print 'Handling run-time error:', detail
  165. ...
  166. Handling run-time error: integer division or modulo by zero
  167. .. _tut-raising:
  168. Raising Exceptions
  169. ==================
  170. The :keyword:`raise` statement allows the programmer to force a specified
  171. exception to occur. For example::
  172. >>> raise NameError('HiThere')
  173. Traceback (most recent call last):
  174. File "<stdin>", line 1, in ?
  175. NameError: HiThere
  176. The sole argument to :keyword:`raise` indicates the exception to be raised.
  177. This must be either an exception instance or an exception class (a class that
  178. derives from :class:`Exception`).
  179. If you need to determine whether an exception was raised but don't intend to
  180. handle it, a simpler form of the :keyword:`raise` statement allows you to
  181. re-raise the exception::
  182. >>> try:
  183. ... raise NameError('HiThere')
  184. ... except NameError:
  185. ... print 'An exception flew by!'
  186. ... raise
  187. ...
  188. An exception flew by!
  189. Traceback (most recent call last):
  190. File "<stdin>", line 2, in ?
  191. NameError: HiThere
  192. .. _tut-userexceptions:
  193. User-defined Exceptions
  194. =======================
  195. Programs may name their own exceptions by creating a new exception class.
  196. Exceptions should typically be derived from the :exc:`Exception` class, either
  197. directly or indirectly. For example::
  198. >>> class MyError(Exception):
  199. ... def __init__(self, value):
  200. ... self.value = value
  201. ... def __str__(self):
  202. ... return repr(self.value)
  203. ...
  204. >>> try:
  205. ... raise MyError(2*2)
  206. ... except MyError as e:
  207. ... print 'My exception occurred, value:', e.value
  208. ...
  209. My exception occurred, value: 4
  210. >>> raise MyError('oops!')
  211. Traceback (most recent call last):
  212. File "<stdin>", line 1, in ?
  213. __main__.MyError: 'oops!'
  214. In this example, the default :meth:`__init__` of :class:`Exception` has been
  215. overridden. The new behavior simply creates the *value* attribute. This
  216. replaces the default behavior of creating the *args* attribute.
  217. Exception classes can be defined which do anything any other class can do, but
  218. are usually kept simple, often only offering a number of attributes that allow
  219. information about the error to be extracted by handlers for the exception. When
  220. creating a module that can raise several distinct errors, a common practice is
  221. to create a base class for exceptions defined by that module, and subclass that
  222. to create specific exception classes for different error conditions::
  223. class Error(Exception):
  224. """Base class for exceptions in this module."""
  225. pass
  226. class InputError(Error):
  227. """Exception raised for errors in the input.
  228. Attributes:
  229. expression -- input expression in which the error occurred
  230. message -- explanation of the error
  231. """
  232. def __init__(self, expression, message):
  233. self.expression = expression
  234. self.message = message
  235. class TransitionError(Error):
  236. """Raised when an operation attempts a state transition that's not
  237. allowed.
  238. Attributes:
  239. previous -- state at beginning of transition
  240. next -- attempted new state
  241. message -- explanation of why the specific transition is not allowed
  242. """
  243. def __init__(self, previous, next, message):
  244. self.previous = previous
  245. self.next = next
  246. self.message = message
  247. Most exceptions are defined with names that end in "Error," similar to the
  248. naming of the standard exceptions.
  249. Many standard modules define their own exceptions to report errors that may
  250. occur in functions they define. More information on classes is presented in
  251. chapter :ref:`tut-classes`.
  252. .. _tut-cleanup:
  253. Defining Clean-up Actions
  254. =========================
  255. The :keyword:`try` statement has another optional clause which is intended to
  256. define clean-up actions that must be executed under all circumstances. For
  257. example::
  258. >>> try:
  259. ... raise KeyboardInterrupt
  260. ... finally:
  261. ... print 'Goodbye, world!'
  262. ...
  263. Goodbye, world!
  264. Traceback (most recent call last):
  265. File "<stdin>", line 2, in ?
  266. KeyboardInterrupt
  267. A *finally clause* is always executed before leaving the :keyword:`try`
  268. statement, whether an exception has occurred or not. When an exception has
  269. occurred in the :keyword:`try` clause and has not been handled by an
  270. :keyword:`except` clause (or it has occurred in a :keyword:`except` or
  271. :keyword:`else` clause), it is re-raised after the :keyword:`finally` clause has
  272. been executed. The :keyword:`finally` clause is also executed "on the way out"
  273. when any other clause of the :keyword:`try` statement is left via a
  274. :keyword:`break`, :keyword:`continue` or :keyword:`return` statement. A more
  275. complicated example (having :keyword:`except` and :keyword:`finally` clauses in
  276. the same :keyword:`try` statement works as of Python 2.5)::
  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
  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 ?
  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
  315. The problem with this code is that it leaves the file open for an indeterminate
  316. amount of time after the code has finished executing. This is not an issue in
  317. simple scripts, but can be a problem for larger applications. The
  318. :keyword:`with` statement allows objects like files to be used in a way that
  319. ensures they are always cleaned up promptly and correctly. ::
  320. with open("myfile.txt") as f:
  321. for line in f:
  322. print line
  323. After the statement is executed, the file *f* is always closed, even if a
  324. problem was encountered while processing the lines. Other objects which provide
  325. predefined clean-up actions will indicate this in their documentation.