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