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
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(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-userexceptions:
271
272User-defined Exceptions
273=======================
274
275Programs may name their own exceptions by creating a new exception class (see
276:ref:`tut-classes` for more about Python classes).  Exceptions should typically
277be derived from the :exc:`Exception` class, either directly or indirectly.
278
279Exception classes can be defined which do anything any other class can do, but
280are usually kept simple, often only offering a number of attributes that allow
281information about the error to be extracted by handlers for the exception.  When
282creating a module that can raise several distinct errors, a common practice is
283to create a base class for exceptions defined by that module, and subclass that
284to create specific exception classes for different error conditions::
285
286   class Error(Exception):
287       """Base class for exceptions in this module."""
288       pass
289
290   class InputError(Error):
291       """Exception raised for errors in the input.
292
293       Attributes:
294           expression -- input expression in which the error occurred
295           message -- explanation of the error
296       """
297
298       def __init__(self, expression, message):
299           self.expression = expression
300           self.message = message
301
302   class TransitionError(Error):
303       """Raised when an operation attempts a state transition that's not
304       allowed.
305
306       Attributes:
307           previous -- state at beginning of transition
308           next -- attempted new state
309           message -- explanation of why the specific transition is not allowed
310       """
311
312       def __init__(self, previous, next, message):
313           self.previous = previous
314           self.next = next
315           self.message = message
316
317Most exceptions are defined with names that end in "Error", similar to the
318naming of the standard exceptions.
319
320Many standard modules define their own exceptions to report errors that may
321occur in functions they define.  More information on classes is presented in
322chapter :ref:`tut-classes`.
323
324
325.. _tut-cleanup:
326
327Defining Clean-up Actions
328=========================
329
330The :keyword:`try` statement has another optional clause which is intended to
331define clean-up actions that must be executed under all circumstances.  For
332example::
333
334   >>> try:
335   ...     raise KeyboardInterrupt
336   ... finally:
337   ...     print('Goodbye, world!')
338   ...
339   Goodbye, world!
340   Traceback (most recent call last):
341     File "<stdin>", line 2, in <module>
342   KeyboardInterrupt
343
344If a :keyword:`finally` clause is present, the :keyword:`!finally`
345clause will execute as the last task before the :keyword:`try`
346statement completes. The :keyword:`!finally` clause runs whether or
347not the :keyword:`!try` statement produces an exception. The following
348points discuss more complex cases when an exception occurs:
349
350* If an exception occurs during execution of the :keyword:`!try`
351  clause, the exception may be handled by an :keyword:`except`
352  clause. If the exception is not handled by an :keyword:`!except`
353  clause, the exception is re-raised after the :keyword:`!finally`
354  clause has been executed.
355
356* An exception could occur during execution of an :keyword:`!except`
357  or :keyword:`!else` clause. Again, the exception is re-raised after
358  the :keyword:`!finally` clause has been executed.
359
360* If the :keyword:`!try` statement reaches a :keyword:`break`,
361  :keyword:`continue` or :keyword:`return` statement, the
362  :keyword:`!finally` clause will execute just prior to the
363  :keyword:`!break`, :keyword:`!continue` or :keyword:`!return`
364  statement's execution.
365
366* If a :keyword:`!finally` clause includes a :keyword:`!return`
367  statement, the returned value will be the one from the
368  :keyword:`!finally` clause's :keyword:`!return` statement, not the
369  value from the :keyword:`!try` clause's :keyword:`!return`
370  statement.
371
372For example::
373
374   >>> def bool_return():
375   ...     try:
376   ...         return True
377   ...     finally:
378   ...         return False
379   ...
380   >>> bool_return()
381   False
382
383A more complicated example::
384
385   >>> def divide(x, y):
386   ...     try:
387   ...         result = x / y
388   ...     except ZeroDivisionError:
389   ...         print("division by zero!")
390   ...     else:
391   ...         print("result is", result)
392   ...     finally:
393   ...         print("executing finally clause")
394   ...
395   >>> divide(2, 1)
396   result is 2.0
397   executing finally clause
398   >>> divide(2, 0)
399   division by zero!
400   executing finally clause
401   >>> divide("2", "1")
402   executing finally clause
403   Traceback (most recent call last):
404     File "<stdin>", line 1, in <module>
405     File "<stdin>", line 3, in divide
406   TypeError: unsupported operand type(s) for /: 'str' and 'str'
407
408As you can see, the :keyword:`finally` clause is executed in any event.  The
409:exc:`TypeError` raised by dividing two strings is not handled by the
410:keyword:`except` clause and therefore re-raised after the :keyword:`!finally`
411clause has been executed.
412
413In real world applications, the :keyword:`finally` clause is useful for
414releasing external resources (such as files or network connections), regardless
415of whether the use of the resource was successful.
416
417
418.. _tut-cleanup-with:
419
420Predefined Clean-up Actions
421===========================
422
423Some objects define standard clean-up actions to be undertaken when the object
424is no longer needed, regardless of whether or not the operation using the object
425succeeded or failed. Look at the following example, which tries to open a file
426and print its contents to the screen. ::
427
428   for line in open("myfile.txt"):
429       print(line, end="")
430
431The problem with this code is that it leaves the file open for an indeterminate
432amount of time after this part of the code has finished executing.
433This is not an issue in simple scripts, but can be a problem for larger
434applications. The :keyword:`with` statement allows objects like files to be
435used in a way that ensures they are always cleaned up promptly and correctly. ::
436
437   with open("myfile.txt") as f:
438       for line in f:
439           print(line, end="")
440
441After the statement is executed, the file *f* is always closed, even if a
442problem was encountered while processing the lines. Objects which, like files,
443provide predefined clean-up actions will indicate this in their documentation.
444
445
446