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