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