• 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 function :func:`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: division 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: Can't convert 'int' object to str implicitly
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
70occurred, 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(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
123A class in an :keyword:`except` clause is compatible with an exception if it is
124the same class or a base class thereof (but not the other way around --- an
125except clause listing a derived class is not compatible with a base class).  For
126example, the following code will print B, C, D in that order::
127
128   class B(Exception):
129       pass
130
131   class C(B):
132       pass
133
134   class D(C):
135       pass
136
137   for cls in [B, C, D]:
138       try:
139           raise cls()
140       except D:
141           print("D")
142       except C:
143           print("C")
144       except B:
145           print("B")
146
147Note that if the except clauses were reversed (with ``except B`` first), it
148would have printed B, B, B --- the first matching except clause is triggered.
149
150The last except clause may omit the exception name(s), to serve as a wildcard.
151Use this with extreme caution, since it is easy to mask a real programming error
152in this way!  It can also be used to print an error message and then re-raise
153the exception (allowing a caller to handle the exception as well)::
154
155   import sys
156
157   try:
158       f = open('myfile.txt')
159       s = f.readline()
160       i = int(s.strip())
161   except OSError as err:
162       print("OS error: {0}".format(err))
163   except ValueError:
164       print("Could not convert data to an integer.")
165   except:
166       print("Unexpected error:", sys.exc_info()[0])
167       raise
168
169The :keyword:`try` ... :keyword:`except` statement has an optional *else
170clause*, which, when present, must follow all except clauses.  It is useful for
171code that must be executed if the try clause does not raise an exception.  For
172example::
173
174   for arg in sys.argv[1:]:
175       try:
176           f = open(arg, 'r')
177       except OSError:
178           print('cannot open', arg)
179       else:
180           print(arg, 'has', len(f.readlines()), 'lines')
181           f.close()
182
183The use of the :keyword:`!else` clause is better than adding additional code to
184the :keyword:`try` clause because it avoids accidentally catching an exception
185that wasn't raised by the code being protected by the :keyword:`!try` ...
186:keyword:`!except` statement.
187
188When an exception occurs, it may have an associated value, also known as the
189exception's *argument*. The presence and type of the argument depend on the
190exception type.
191
192The except clause may specify a variable after the exception name.  The
193variable is bound to an exception instance with the arguments stored in
194``instance.args``.  For convenience, the exception instance defines
195:meth:`__str__` so the arguments can be printed directly without having to
196reference ``.args``.  One may also instantiate an exception first before
197raising it and add any attributes to it as desired. ::
198
199   >>> try:
200   ...     raise Exception('spam', 'eggs')
201   ... except Exception as inst:
202   ...     print(type(inst))    # the exception instance
203   ...     print(inst.args)     # arguments stored in .args
204   ...     print(inst)          # __str__ allows args to be printed directly,
205   ...                          # but may be overridden in exception subclasses
206   ...     x, y = inst.args     # unpack args
207   ...     print('x =', x)
208   ...     print('y =', y)
209   ...
210   <class 'Exception'>
211   ('spam', 'eggs')
212   ('spam', 'eggs')
213   x = spam
214   y = eggs
215
216If an exception has arguments, they are printed as the last part ('detail') of
217the message for unhandled exceptions.
218
219Exception handlers don't just handle exceptions if they occur immediately in the
220try clause, but also if they occur inside functions that are called (even
221indirectly) in the try clause. For example::
222
223   >>> def this_fails():
224   ...     x = 1/0
225   ...
226   >>> try:
227   ...     this_fails()
228   ... except ZeroDivisionError as err:
229   ...     print('Handling run-time error:', err)
230   ...
231   Handling run-time error: division by zero
232
233
234.. _tut-raising:
235
236Raising Exceptions
237==================
238
239The :keyword:`raise` statement allows the programmer to force a specified
240exception to occur. For example::
241
242   >>> raise NameError('HiThere')
243   Traceback (most recent call last):
244     File "<stdin>", line 1, in <module>
245   NameError: HiThere
246
247The sole argument to :keyword:`raise` indicates the exception to be raised.
248This must be either an exception instance or an exception class (a class that
249derives from :class:`Exception`).  If an exception class is passed, it will
250be implicitly instantiated by calling its constructor with no arguments::
251
252   raise ValueError  # shorthand for 'raise ValueError()'
253
254If you need to determine whether an exception was raised but don't intend to
255handle it, a simpler form of the :keyword:`raise` statement allows you to
256re-raise the exception::
257
258   >>> try:
259   ...     raise NameError('HiThere')
260   ... except NameError:
261   ...     print('An exception flew by!')
262   ...     raise
263   ...
264   An exception flew by!
265   Traceback (most recent call last):
266     File "<stdin>", line 2, in <module>
267   NameError: HiThere
268
269
270.. _tut-exception-chaining:
271
272Exception Chaining
273==================
274
275The :keyword:`raise` statement allows an optional :keyword:`from` which enables
276chaining exceptions. For example::
277
278    # exc must be exception instance or None.
279    raise RuntimeError from exc
280
281This can be useful when you are transforming exceptions. For example::
282
283    >>> def func():
284    ...     raise IOError
285    ...
286    >>> try:
287    ...     func()
288    ... except IOError as exc:
289    ...     raise RuntimeError('Failed to open database') from exc
290    ...
291    Traceback (most recent call last):
292      File "<stdin>", line 2, in <module>
293      File "<stdin>", line 2, in func
294    OSError
295    <BLANKLINE>
296    The above exception was the direct cause of the following exception:
297    <BLANKLINE>
298    Traceback (most recent call last):
299      File "<stdin>", line 4, in <module>
300    RuntimeError: Failed to open database
301
302Exception chaining happens automatically when an exception is raised inside an
303:keyword:`except` or :keyword:`finally` section. Exception chaining can be
304disabled by using ``from None`` idiom:
305
306    >>> try:
307    ...     open('database.sqlite')
308    ... except IOError:
309    ...     raise RuntimeError from None
310    ...
311    Traceback (most recent call last):
312      File "<stdin>", line 4, in <module>
313    RuntimeError
314
315For more information about chaining mechanics, see :ref:`bltin-exceptions`.
316
317
318.. _tut-userexceptions:
319
320User-defined Exceptions
321=======================
322
323Programs may name their own exceptions by creating a new exception class (see
324:ref:`tut-classes` for more about Python classes).  Exceptions should typically
325be derived from the :exc:`Exception` class, either directly or indirectly.
326
327Exception classes can be defined which do anything any other class can do, but
328are usually kept simple, often only offering a number of attributes that allow
329information about the error to be extracted by handlers for the exception.  When
330creating a module that can raise several distinct errors, a common practice is
331to create a base class for exceptions defined by that module, and subclass that
332to create specific exception classes for different error conditions::
333
334   class Error(Exception):
335       """Base class for exceptions in this module."""
336       pass
337
338   class InputError(Error):
339       """Exception raised for errors in the input.
340
341       Attributes:
342           expression -- input expression in which the error occurred
343           message -- explanation of the error
344       """
345
346       def __init__(self, expression, message):
347           self.expression = expression
348           self.message = message
349
350   class TransitionError(Error):
351       """Raised when an operation attempts a state transition that's not
352       allowed.
353
354       Attributes:
355           previous -- state at beginning of transition
356           next -- attempted new state
357           message -- explanation of why the specific transition is not allowed
358       """
359
360       def __init__(self, previous, next, message):
361           self.previous = previous
362           self.next = next
363           self.message = message
364
365Most exceptions are defined with names that end in "Error", similar to the
366naming of the standard exceptions.
367
368Many standard modules define their own exceptions to report errors that may
369occur in functions they define.  More information on classes is presented in
370chapter :ref:`tut-classes`.
371
372
373.. _tut-cleanup:
374
375Defining Clean-up Actions
376=========================
377
378The :keyword:`try` statement has another optional clause which is intended to
379define clean-up actions that must be executed under all circumstances.  For
380example::
381
382   >>> try:
383   ...     raise KeyboardInterrupt
384   ... finally:
385   ...     print('Goodbye, world!')
386   ...
387   Goodbye, world!
388   Traceback (most recent call last):
389     File "<stdin>", line 2, in <module>
390   KeyboardInterrupt
391
392If a :keyword:`finally` clause is present, the :keyword:`!finally`
393clause will execute as the last task before the :keyword:`try`
394statement completes. The :keyword:`!finally` clause runs whether or
395not the :keyword:`!try` statement produces an exception. The following
396points discuss more complex cases when an exception occurs:
397
398* If an exception occurs during execution of the :keyword:`!try`
399  clause, the exception may be handled by an :keyword:`except`
400  clause. If the exception is not handled by an :keyword:`!except`
401  clause, the exception is re-raised after the :keyword:`!finally`
402  clause has been executed.
403
404* An exception could occur during execution of an :keyword:`!except`
405  or :keyword:`!else` clause. Again, the exception is re-raised after
406  the :keyword:`!finally` clause has been executed.
407
408* If the :keyword:`!try` statement reaches a :keyword:`break`,
409  :keyword:`continue` or :keyword:`return` statement, the
410  :keyword:`!finally` clause will execute just prior to the
411  :keyword:`!break`, :keyword:`!continue` or :keyword:`!return`
412  statement's execution.
413
414* If a :keyword:`!finally` clause includes a :keyword:`!return`
415  statement, the returned value will be the one from the
416  :keyword:`!finally` clause's :keyword:`!return` statement, not the
417  value from the :keyword:`!try` clause's :keyword:`!return`
418  statement.
419
420For example::
421
422   >>> def bool_return():
423   ...     try:
424   ...         return True
425   ...     finally:
426   ...         return False
427   ...
428   >>> bool_return()
429   False
430
431A more complicated example::
432
433   >>> def divide(x, y):
434   ...     try:
435   ...         result = x / y
436   ...     except ZeroDivisionError:
437   ...         print("division by zero!")
438   ...     else:
439   ...         print("result is", result)
440   ...     finally:
441   ...         print("executing finally clause")
442   ...
443   >>> divide(2, 1)
444   result is 2.0
445   executing finally clause
446   >>> divide(2, 0)
447   division by zero!
448   executing finally clause
449   >>> divide("2", "1")
450   executing finally clause
451   Traceback (most recent call last):
452     File "<stdin>", line 1, in <module>
453     File "<stdin>", line 3, in divide
454   TypeError: unsupported operand type(s) for /: 'str' and 'str'
455
456As you can see, the :keyword:`finally` clause is executed in any event.  The
457:exc:`TypeError` raised by dividing two strings is not handled by the
458:keyword:`except` clause and therefore re-raised after the :keyword:`!finally`
459clause has been executed.
460
461In real world applications, the :keyword:`finally` clause is useful for
462releasing external resources (such as files or network connections), regardless
463of whether the use of the resource was successful.
464
465
466.. _tut-cleanup-with:
467
468Predefined Clean-up Actions
469===========================
470
471Some objects define standard clean-up actions to be undertaken when the object
472is no longer needed, regardless of whether or not the operation using the object
473succeeded or failed. Look at the following example, which tries to open a file
474and print its contents to the screen. ::
475
476   for line in open("myfile.txt"):
477       print(line, end="")
478
479The problem with this code is that it leaves the file open for an indeterminate
480amount of time after this part of the code has finished executing.
481This is not an issue in simple scripts, but can be a problem for larger
482applications. The :keyword:`with` statement allows objects like files to be
483used in a way that ensures they are always cleaned up promptly and correctly. ::
484
485   with open("myfile.txt") as f:
486       for line in f:
487           print(line, end="")
488
489After the statement is executed, the file *f* is always closed, even if a
490problem was encountered while processing the lines. Objects which, like files,
491provide predefined clean-up actions will indicate this in their documentation.
492
493
494