rest25/tutorial/errors.rst => rest262/tutorial/errors.rst
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
n74-The Python Library Reference (XXX reference: ../lib/module-exceptions.html)
n74+:ref:`bltin-exceptions` lists the built-in exceptions and their meanings.
75-lists the built-in exceptions and their meanings.
76
77
78.. _tut-handling:
79
80Handling Exceptions
81===================
82
83It is possible to write programs that handle selected exceptions. Look at the
87is signalled by raising the :exc:`KeyboardInterrupt` exception. ::
88
89   >>> while True:
90   ...     try:
91   ...         x = int(raw_input("Please enter a number: "))
92   ...         break
93   ...     except ValueError:
94   ...         print "Oops!  That was no valid number.  Try again..."
n95-   ...     
n94+   ...
96
97The :keyword:`try` statement works as follows.
98
99* First, the *try clause* (the statement(s) between the :keyword:`try` and
100  :keyword:`except` keywords) is executed.
101
102* If no exception occurs, the *except clause* is skipped and execution of the
103  :keyword:`try` statement is finished.
127the exception (allowing a caller to handle the exception as well)::
128
129   import sys
130
131   try:
132       f = open('myfile.txt')
133       s = f.readline()
134       i = int(s.strip())
n135-   except IOError, (errno, strerror):
n134+   except IOError as (errno, strerror):
136-       print "I/O error(%s): %s" % (errno, strerror)
135+       print "I/O error({0}): {1}".format(errno, strerror)
137   except ValueError:
138       print "Could not convert data to an integer."
139   except:
140       print "Unexpected error:", sys.exc_info()[0]
141       raise
142
143The :keyword:`try` ... :keyword:`except` statement has an optional *else
144clause*, which, when present, must follow all except clauses.  It is useful for
166The except clause may specify a variable after the exception name (or tuple).
167The variable is bound to an exception instance with the arguments stored in
168``instance.args``.  For convenience, the exception instance defines
169:meth:`__getitem__` and :meth:`__str__` so the arguments can be accessed or
170printed directly without having to reference ``.args``.
171
172But use of ``.args`` is discouraged.  Instead, the preferred use is to pass a
173single argument to an exception (which can be a tuple if multiple arguments are
n174-needed) and have it bound to the ``message`` attribute.  One my also instantiate
n173+needed) and have it bound to the ``message`` attribute.  One may also
175-an exception first before raising it and add any attributes to it as desired. ::
174+instantiate an exception first before raising it and add any attributes to it as
175+desired. ::
176
177   >>> try:
178   ...    raise Exception('spam', 'eggs')
n179-   ... except Exception, inst:
n179+   ... 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   ...
n187-   <type 'instance'>
n187+   <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
n202-   ... 
n202+   ...
203   >>> try:
204   ...     this_fails()
n205-   ... except ZeroDivisionError, detail:
n205+   ... except ZeroDivisionError as detail:
206   ...     print 'Handling run-time error:', detail
n207-   ... 
n207+   ...
208   Handling run-time error: integer division or modulo by zero
209
210
211.. _tut-raising:
212
213Raising Exceptions
214==================
215
222   NameError: HiThere
223
224The first argument to :keyword:`raise` names the exception to be raised.  The
225optional second argument specifies the exception's argument.  Alternatively, the
226above could be written as ``raise NameError('HiThere')``.  Either form works
227fine, but there seems to be a growing stylistic preference for the latter.
228
229If you need to determine whether an exception was raised but don't intend to
n230-handle it, a simpler form of the :keyword:`raise` statement allows you to re-
n230+handle it, a simpler form of the :keyword:`raise` statement allows you to
231-raise the exception::
231+re-raise the exception::
232
233   >>> try:
234   ...     raise NameError, 'HiThere'
235   ... except NameError:
236   ...     print 'An exception flew by!'
237   ...     raise
238   ...
239   An exception flew by!
251Exceptions should typically be derived from the :exc:`Exception` class, either
252directly or indirectly.  For example::
253
254   >>> class MyError(Exception):
255   ...     def __init__(self, value):
256   ...         self.value = value
257   ...     def __str__(self):
258   ...         return repr(self.value)
n259-   ... 
n259+   ...
260   >>> try:
261   ...     raise MyError(2*2)
n262-   ... except MyError, e:
n262+   ... except MyError as e:
263   ...     print 'My exception occurred, value:', e.value
n264-   ... 
n264+   ...
265   My exception occurred, value: 4
266   >>> raise MyError, 'oops!'
267   Traceback (most recent call last):
268     File "<stdin>", line 1, in ?
269   __main__.MyError: 'oops!'
270
271In this example, the default :meth:`__init__` of :class:`Exception` has been
272overridden.  The new behavior simply creates the *value* attribute.  This
310           self.next = next
311           self.message = message
312
313Most exceptions are defined with names that end in "Error," similar to the
314naming of the standard exceptions.
315
316Many standard modules define their own exceptions to report errors that may
317occur in functions they define.  More information on classes is presented in
n318-chapter :ref:`tut-classes`, "Classes."
n318+chapter :ref:`tut-classes`.
319
320
321.. _tut-cleanup:
322
323Defining Clean-up Actions
324=========================
325
326The :keyword:`try` statement has another optional clause which is intended to
327define clean-up actions that must be executed under all circumstances.  For
328example::
329
330   >>> try:
331   ...     raise KeyboardInterrupt
332   ... finally:
333   ...     print 'Goodbye, world!'
n334-   ... 
n334+   ...
335   Goodbye, world!
336   Traceback (most recent call last):
337     File "<stdin>", line 2, in ?
338   KeyboardInterrupt
339
340A *finally clause* is always executed before leaving the :keyword:`try`
341statement, whether an exception has occurred or not. When an exception has
342occurred in the :keyword:`try` clause and has not been handled by an
343:keyword:`except` clause (or it has occurred in a :keyword:`except` or
344:keyword:`else` clause), it is re-raised after the :keyword:`finally` clause has
345been executed.  The :keyword:`finally` clause is also executed "on the way out"
346when any other clause of the :keyword:`try` statement is left via a
347:keyword:`break`, :keyword:`continue` or :keyword:`return` statement.  A more
n348-complicated example::
n348+complicated example (having :keyword:`except` and :keyword:`finally` clauses in
349+the 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
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`
t376-clauses has been executed.
t377+clause 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
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op