PageRenderTime 38ms CodeModel.GetById 22ms app.highlight 11ms RepoModel.GetById 1ms app.codeStats 0ms

/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*********************
  4Errors and Exceptions
  5*********************
  6
  7Until now error messages haven't been more than mentioned, but if you have tried
  8out the examples you have probably seen some.  There are (at least) two
  9distinguishable kinds of errors: *syntax errors* and *exceptions*.
 10
 11
 12.. _tut-syntaxerrors:
 13
 14Syntax Errors
 15=============
 16
 17Syntax errors, also known as parsing errors, are perhaps the most common kind of
 18complaint you get while you are still learning Python::
 19
 20   >>> while True print 'Hello world'
 21     File "<stdin>", line 1, in ?
 22       while True print 'Hello world'
 23                      ^
 24   SyntaxError: invalid syntax
 25
 26The parser repeats the offending line and displays a little 'arrow' pointing at
 27the earliest point in the line where the error was detected.  The error is
 28caused by (or at least detected at) the token *preceding* the arrow: in the
 29example, the error is detected at the keyword :keyword:`print`, since a colon
 30(``':'``) is missing before it.  File name and line number are printed so you
 31know where to look in case the input came from a script.
 32
 33
 34.. _tut-exceptions:
 35
 36Exceptions
 37==========
 38
 39Even if a statement or expression is syntactically correct, it may cause an
 40error when an attempt is made to execute it. Errors detected during execution
 41are called *exceptions* and are not unconditionally fatal: you will soon learn
 42how to handle them in Python programs.  Most exceptions are not handled by
 43programs, however, and result in error messages as shown here::
 44
 45   >>> 10 * (1/0)
 46   Traceback (most recent call last):
 47     File "<stdin>", line 1, in ?
 48   ZeroDivisionError: integer division or modulo by zero
 49   >>> 4 + spam*3
 50   Traceback (most recent call last):
 51     File "<stdin>", line 1, in ?
 52   NameError: name 'spam' is not defined
 53   >>> '2' + 2
 54   Traceback (most recent call last):
 55     File "<stdin>", line 1, in ?
 56   TypeError: cannot concatenate 'str' and 'int' objects
 57
 58The last line of the error message indicates what happened. Exceptions come in
 59different types, and the type is printed as part of the message: the types in
 60the example are :exc:`ZeroDivisionError`, :exc:`NameError` and :exc:`TypeError`.
 61The string printed as the exception type is the name of the built-in exception
 62that occurred.  This is true for all built-in exceptions, but need not be true
 63for user-defined exceptions (although it is a useful convention). Standard
 64exception names are built-in identifiers (not reserved keywords).
 65
 66The rest of the line provides detail based on the type of exception and what
 67caused it.
 68
 69The preceding part of the error message shows the context where the exception
 70happened, in the form of a stack traceback. In general it contains a stack
 71traceback listing source lines; however, it will not display lines read from
 72standard input.
 73
 74:ref:`bltin-exceptions` lists the built-in exceptions and their meanings.
 75
 76
 77.. _tut-handling:
 78
 79Handling Exceptions
 80===================
 81
 82It is possible to write programs that handle selected exceptions. Look at the
 83following example, which asks the user for input until a valid integer has been
 84entered, but allows the user to interrupt the program (using :kbd:`Control-C` or
 85whatever the operating system supports); note that a user-generated interruption
 86is signalled by raising the :exc:`KeyboardInterrupt` exception. ::
 87
 88   >>> while True:
 89   ...     try:
 90   ...         x = int(raw_input("Please enter a number: "))
 91   ...         break
 92   ...     except ValueError:
 93   ...         print "Oops!  That was no valid number.  Try again..."
 94   ...
 95
 96The :keyword:`try` statement works as follows.
 97
 98* First, the *try clause* (the statement(s) between the :keyword:`try` and
 99  :keyword:`except` keywords) is executed.
100
101* If no exception occurs, the *except clause* is skipped and execution of the
102  :keyword:`try` statement is finished.
103
104* If an exception occurs during execution of the try clause, the rest of the
105  clause is skipped.  Then if its type matches the exception named after the
106  :keyword:`except` keyword, the except clause is executed, and then execution
107  continues after the :keyword:`try` statement.
108
109* If an exception occurs which does not match the exception named in the except
110  clause, it is passed on to outer :keyword:`try` statements; if no handler is
111  found, it is an *unhandled exception* and execution stops with a message as
112  shown above.
113
114A :keyword:`try` statement may have more than one except clause, to specify
115handlers for different exceptions.  At most one handler will be executed.
116Handlers only handle exceptions that occur in the corresponding try clause, not
117in other handlers of the same :keyword:`try` statement.  An except clause may
118name multiple exceptions as a parenthesized tuple, for example::
119
120   ... except (RuntimeError, TypeError, NameError):
121   ...     pass
122
123The last except clause may omit the exception name(s), to serve as a wildcard.
124Use this with extreme caution, since it is easy to mask a real programming error
125in this way!  It can also be used to print an error message and then re-raise
126the exception (allowing a caller to handle the exception as well)::
127
128   import sys
129
130   try:
131       f = open('myfile.txt')
132       s = f.readline()
133       i = int(s.strip())
134   except IOError as (errno, strerror):
135       print "I/O error({0}): {1}".format(errno, strerror)
136   except ValueError:
137       print "Could not convert data to an integer."
138   except:
139       print "Unexpected error:", sys.exc_info()[0]
140       raise
141
142The :keyword:`try` ... :keyword:`except` statement has an optional *else
143clause*, which, when present, must follow all except clauses.  It is useful for
144code that must be executed if the try clause does not raise an exception.  For
145example::
146
147   for arg in sys.argv[1:]:
148       try:
149           f = open(arg, 'r')
150       except IOError:
151           print 'cannot open', arg
152       else:
153           print arg, 'has', len(f.readlines()), 'lines'
154           f.close()
155
156The use of the :keyword:`else` clause is better than adding additional code to
157the :keyword:`try` clause because it avoids accidentally catching an exception
158that wasn't raised by the code being protected by the :keyword:`try` ...
159:keyword:`except` statement.
160
161When an exception occurs, it may have an associated value, also known as the
162exception's *argument*. The presence and type of the argument depend on the
163exception type.
164
165The except clause may specify a variable after the exception name (or tuple).
166The variable is bound to an exception instance with the arguments stored in
167``instance.args``.  For convenience, the exception instance defines
168:meth:`__getitem__` and :meth:`__str__` so the arguments can be accessed or
169printed directly without having to reference ``.args``.
170
171But use of ``.args`` is discouraged.  Instead, the preferred use is to pass a
172single argument to an exception (which can be a tuple if multiple arguments are
173needed) and have it bound to the ``message`` attribute.  One may also
174instantiate an exception first before raising it and add any attributes to it as
175desired. ::
176
177   >>> try:
178   ...    raise Exception('spam', 'eggs')
179   ... except Exception as inst:
180   ...    print type(inst)     # the exception instance
181   ...    print inst.args      # arguments stored in .args
182   ...    print inst           # __str__ allows args to printed directly
183   ...    x, y = inst          # __getitem__ allows args to be unpacked directly
184   ...    print 'x =', x
185   ...    print 'y =', y
186   ...
187   <type 'exceptions.Exception'>
188   ('spam', 'eggs')
189   ('spam', 'eggs')
190   x = spam
191   y = eggs
192
193If an exception has an argument, it is printed as the last part ('detail') of
194the message for unhandled exceptions.
195
196Exception handlers don't just handle exceptions if they occur immediately in the
197try clause, but also if they occur inside functions that are called (even
198indirectly) in the try clause. For example::
199
200   >>> def this_fails():
201   ...     x = 1/0
202   ...
203   >>> try:
204   ...     this_fails()
205   ... except ZeroDivisionError as detail:
206   ...     print 'Handling run-time error:', detail
207   ...
208   Handling run-time error: integer division or modulo by zero
209
210
211.. _tut-raising:
212
213Raising Exceptions
214==================
215
216The :keyword:`raise` statement allows the programmer to force a specified
217exception to occur. For example::
218
219   >>> raise NameError('HiThere')
220   Traceback (most recent call last):
221     File "<stdin>", line 1, in ?
222   NameError: HiThere
223
224The sole argument to :keyword:`raise` indicates the exception to be raised.
225This must be either an exception instance or an exception class (a class that
226derives from :class:`Exception`).
227
228If you need to determine whether an exception was raised but don't intend to
229handle it, a simpler form of the :keyword:`raise` statement allows you to
230re-raise the exception::
231
232   >>> try:
233   ...     raise NameError('HiThere')
234   ... except NameError:
235   ...     print 'An exception flew by!'
236   ...     raise
237   ...
238   An exception flew by!
239   Traceback (most recent call last):
240     File "<stdin>", line 2, in ?
241   NameError: HiThere
242
243
244.. _tut-userexceptions:
245
246User-defined Exceptions
247=======================
248
249Programs may name their own exceptions by creating a new exception class.
250Exceptions should typically be derived from the :exc:`Exception` class, either
251directly or indirectly.  For example::
252
253   >>> class MyError(Exception):
254   ...     def __init__(self, value):
255   ...         self.value = value
256   ...     def __str__(self):
257   ...         return repr(self.value)
258   ...
259   >>> try:
260   ...     raise MyError(2*2)
261   ... except MyError as e:
262   ...     print 'My exception occurred, value:', e.value
263   ...
264   My exception occurred, value: 4
265   >>> raise MyError('oops!')
266   Traceback (most recent call last):
267     File "<stdin>", line 1, in ?
268   __main__.MyError: 'oops!'
269
270In this example, the default :meth:`__init__` of :class:`Exception` has been
271overridden.  The new behavior simply creates the *value* attribute.  This
272replaces the default behavior of creating the *args* attribute.
273
274Exception classes can be defined which do anything any other class can do, but
275are usually kept simple, often only offering a number of attributes that allow
276information about the error to be extracted by handlers for the exception.  When
277creating a module that can raise several distinct errors, a common practice is
278to create a base class for exceptions defined by that module, and subclass that
279to create specific exception classes for different error conditions::
280
281   class Error(Exception):
282       """Base class for exceptions in this module."""
283       pass
284
285   class InputError(Error):
286       """Exception raised for errors in the input.
287
288       Attributes:
289           expression -- input expression in which the error occurred
290           message -- explanation of the error
291       """
292
293       def __init__(self, expression, message):
294           self.expression = expression
295           self.message = message
296
297   class TransitionError(Error):
298       """Raised when an operation attempts a state transition that's not
299       allowed.
300
301       Attributes:
302           previous -- state at beginning of transition
303           next -- attempted new state
304           message -- explanation of why the specific transition is not allowed
305       """
306
307       def __init__(self, previous, next, message):
308           self.previous = previous
309           self.next = next
310           self.message = message
311
312Most exceptions are defined with names that end in "Error," similar to the
313naming of the standard exceptions.
314
315Many standard modules define their own exceptions to report errors that may
316occur in functions they define.  More information on classes is presented in
317chapter :ref:`tut-classes`.
318
319
320.. _tut-cleanup:
321
322Defining Clean-up Actions
323=========================
324
325The :keyword:`try` statement has another optional clause which is intended to
326define clean-up actions that must be executed under all circumstances.  For
327example::
328
329   >>> try:
330   ...     raise KeyboardInterrupt
331   ... finally:
332   ...     print 'Goodbye, world!'
333   ...
334   Goodbye, world!
335   Traceback (most recent call last):
336     File "<stdin>", line 2, in ?
337   KeyboardInterrupt
338
339A *finally clause* is always executed before leaving the :keyword:`try`
340statement, whether an exception has occurred or not. When an exception has
341occurred in the :keyword:`try` clause and has not been handled by an
342:keyword:`except` clause (or it has occurred in a :keyword:`except` or
343:keyword:`else` clause), it is re-raised after the :keyword:`finally` clause has
344been executed.  The :keyword:`finally` clause is also executed "on the way out"
345when any other clause of the :keyword:`try` statement is left via a
346:keyword:`break`, :keyword:`continue` or :keyword:`return` statement.  A more
347complicated example (having :keyword:`except` and :keyword:`finally` clauses in
348the same :keyword:`try` statement works as of Python 2.5)::
349
350   >>> def divide(x, y):
351   ...     try:
352   ...         result = x / y
353   ...     except ZeroDivisionError:
354   ...         print "division by zero!"
355   ...     else:
356   ...         print "result is", result
357   ...     finally:
358   ...         print "executing finally clause"
359   ...
360   >>> divide(2, 1)
361   result is 2
362   executing finally clause
363   >>> divide(2, 0)
364   division by zero!
365   executing finally clause
366   >>> divide("2", "1")
367   executing finally clause
368   Traceback (most recent call last):
369     File "<stdin>", line 1, in ?
370     File "<stdin>", line 3, in divide
371   TypeError: unsupported operand type(s) for /: 'str' and 'str'
372
373As you can see, the :keyword:`finally` clause is executed in any event.  The
374:exc:`TypeError` raised by dividing two strings is not handled by the
375:keyword:`except` clause and therefore re-raised after the :keyword:`finally`
376clause has been executed.
377
378In real world applications, the :keyword:`finally` clause is useful for
379releasing external resources (such as files or network connections), regardless
380of whether the use of the resource was successful.
381
382
383.. _tut-cleanup-with:
384
385Predefined Clean-up Actions
386===========================
387
388Some objects define standard clean-up actions to be undertaken when the object
389is no longer needed, regardless of whether or not the operation using the object
390succeeded or failed. Look at the following example, which tries to open a file
391and print its contents to the screen. ::
392
393   for line in open("myfile.txt"):
394       print line
395
396The problem with this code is that it leaves the file open for an indeterminate
397amount of time after the code has finished executing. This is not an issue in
398simple scripts, but can be a problem for larger applications. The
399:keyword:`with` statement allows objects like files to be used in a way that
400ensures they are always cleaned up promptly and correctly. ::
401
402   with open("myfile.txt") as f:
403       for line in f:
404           print line
405
406After the statement is executed, the file *f* is always closed, even if a
407problem was encountered while processing the lines. Other objects which provide
408predefined clean-up actions will indicate this in their documentation.
409
410