• 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 little arrows pointing
27at the token in the line where the error was detected.  The error may be
28caused by the absence of a token *before* the indicated token.  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       10 * (1/0)
49             ~^~
50   ZeroDivisionError: division by zero
51   >>> 4 + spam*3
52   Traceback (most recent call last):
53     File "<stdin>", line 1, in <module>
54       4 + spam*3
55           ^^^^
56   NameError: name 'spam' is not defined
57   >>> '2' + 2
58   Traceback (most recent call last):
59     File "<stdin>", line 1, in <module>
60       '2' + 2
61       ~~~~^~~
62   TypeError: can only concatenate str (not "int") to str
63
64The last line of the error message indicates what happened. Exceptions come in
65different types, and the type is printed as part of the message: the types in
66the example are :exc:`ZeroDivisionError`, :exc:`NameError` and :exc:`TypeError`.
67The string printed as the exception type is the name of the built-in exception
68that occurred.  This is true for all built-in exceptions, but need not be true
69for user-defined exceptions (although it is a useful convention). Standard
70exception names are built-in identifiers (not reserved keywords).
71
72The rest of the line provides detail based on the type of exception and what
73caused it.
74
75The preceding part of the error message shows the context where the exception
76occurred, in the form of a stack traceback. In general it contains a stack
77traceback listing source lines; however, it will not display lines read from
78standard input.
79
80:ref:`bltin-exceptions` lists the built-in exceptions and their meanings.
81
82
83.. _tut-handling:
84
85Handling Exceptions
86===================
87
88It is possible to write programs that handle selected exceptions. Look at the
89following example, which asks the user for input until a valid integer has been
90entered, but allows the user to interrupt the program (using :kbd:`Control-C` or
91whatever the operating system supports); note that a user-generated interruption
92is signalled by raising the :exc:`KeyboardInterrupt` exception. ::
93
94   >>> while True:
95   ...     try:
96   ...         x = int(input("Please enter a number: "))
97   ...         break
98   ...     except ValueError:
99   ...         print("Oops!  That was no valid number.  Try again...")
100   ...
101
102The :keyword:`try` statement works as follows.
103
104* First, the *try clause* (the statement(s) between the :keyword:`try` and
105  :keyword:`except` keywords) is executed.
106
107* If no exception occurs, the *except clause* is skipped and execution of the
108  :keyword:`try` statement is finished.
109
110* If an exception occurs during execution of the :keyword:`try` clause, the rest of the
111  clause is skipped.  Then, if its type matches the exception named after the
112  :keyword:`except` keyword, the *except clause* is executed, and then execution
113  continues after the try/except block.
114
115* If an exception occurs which does not match the exception named in the *except
116  clause*, it is passed on to outer :keyword:`try` statements; if no handler is
117  found, it is an *unhandled exception* and execution stops with an error message.
118
119A :keyword:`try` statement may have more than one *except clause*, to specify
120handlers for different exceptions.  At most one handler will be executed.
121Handlers only handle exceptions that occur in the corresponding *try clause*,
122not in other handlers of the same :keyword:`!try` statement.  An *except clause*
123may name multiple exceptions as a parenthesized tuple, for example::
124
125   ... except (RuntimeError, TypeError, NameError):
126   ...     pass
127
128A class in an :keyword:`except` clause matches exceptions which are instances of the
129class itself or one of its derived classes (but not the other way around --- an
130*except clause* listing a derived class does not match instances of its base classes).
131For example, the following code will print B, C, D in that order::
132
133   class B(Exception):
134       pass
135
136   class C(B):
137       pass
138
139   class D(C):
140       pass
141
142   for cls in [B, C, D]:
143       try:
144           raise cls()
145       except D:
146           print("D")
147       except C:
148           print("C")
149       except B:
150           print("B")
151
152Note that if the *except clauses* were reversed (with ``except B`` first), it
153would have printed B, B, B --- the first matching *except clause* is triggered.
154
155When an exception occurs, it may have associated values, also known as the
156exception's *arguments*. The presence and types of the arguments depend on the
157exception type.
158
159The *except clause* may specify a variable after the exception name.  The
160variable is bound to the exception instance which typically has an ``args``
161attribute that stores the arguments. For convenience, builtin exception
162types define :meth:`~object.__str__` to print all the arguments without explicitly
163accessing ``.args``.  ::
164
165   >>> try:
166   ...     raise Exception('spam', 'eggs')
167   ... except Exception as inst:
168   ...     print(type(inst))    # the exception type
169   ...     print(inst.args)     # arguments stored in .args
170   ...     print(inst)          # __str__ allows args to be printed directly,
171   ...                          # but may be overridden in exception subclasses
172   ...     x, y = inst.args     # unpack args
173   ...     print('x =', x)
174   ...     print('y =', y)
175   ...
176   <class 'Exception'>
177   ('spam', 'eggs')
178   ('spam', 'eggs')
179   x = spam
180   y = eggs
181
182The exception's :meth:`~object.__str__` output is printed as the last part ('detail')
183of the message for unhandled exceptions.
184
185:exc:`BaseException` is the common base class of all exceptions. One of its
186subclasses, :exc:`Exception`, is the base class of all the non-fatal exceptions.
187Exceptions which are not subclasses of :exc:`Exception` are not typically
188handled, because they are used to indicate that the program should terminate.
189They include :exc:`SystemExit` which is raised by :meth:`sys.exit` and
190:exc:`KeyboardInterrupt` which is raised when a user wishes to interrupt
191the program.
192
193:exc:`Exception` can be used as a wildcard that catches (almost) everything.
194However, it is good practice to be as specific as possible with the types
195of exceptions that we intend to handle, and to allow any unexpected
196exceptions to propagate on.
197
198The most common pattern for handling :exc:`Exception` is to print or log
199the exception and then re-raise it (allowing a caller to handle the
200exception as well)::
201
202   import sys
203
204   try:
205       f = open('myfile.txt')
206       s = f.readline()
207       i = int(s.strip())
208   except OSError as err:
209       print("OS error:", err)
210   except ValueError:
211       print("Could not convert data to an integer.")
212   except Exception as err:
213       print(f"Unexpected {err=}, {type(err)=}")
214       raise
215
216The :keyword:`try` ... :keyword:`except` statement has an optional *else
217clause*, which, when present, must follow all *except clauses*.  It is useful
218for code that must be executed if the *try clause* does not raise an exception.
219For example::
220
221   for arg in sys.argv[1:]:
222       try:
223           f = open(arg, 'r')
224       except OSError:
225           print('cannot open', arg)
226       else:
227           print(arg, 'has', len(f.readlines()), 'lines')
228           f.close()
229
230The use of the :keyword:`!else` clause is better than adding additional code to
231the :keyword:`try` clause because it avoids accidentally catching an exception
232that wasn't raised by the code being protected by the :keyword:`!try` ...
233:keyword:`!except` statement.
234
235Exception handlers do not handle only exceptions that occur immediately in the
236*try clause*, but also those that occur inside functions that are called (even
237indirectly) in the *try clause*. For example::
238
239   >>> def this_fails():
240   ...     x = 1/0
241   ...
242   >>> try:
243   ...     this_fails()
244   ... except ZeroDivisionError as err:
245   ...     print('Handling run-time error:', err)
246   ...
247   Handling run-time error: division by zero
248
249
250.. _tut-raising:
251
252Raising Exceptions
253==================
254
255The :keyword:`raise` statement allows the programmer to force a specified
256exception to occur. For example::
257
258   >>> raise NameError('HiThere')
259   Traceback (most recent call last):
260     File "<stdin>", line 1, in <module>
261       raise NameError('HiThere')
262   NameError: HiThere
263
264The sole argument to :keyword:`raise` indicates the exception to be raised.
265This must be either an exception instance or an exception class (a class that
266derives from :class:`BaseException`, such as :exc:`Exception` or one of its
267subclasses).  If an exception class is passed, it will be implicitly
268instantiated by calling its constructor with no arguments::
269
270   raise ValueError  # shorthand for 'raise ValueError()'
271
272If you need to determine whether an exception was raised but don't intend to
273handle it, a simpler form of the :keyword:`raise` statement allows you to
274re-raise the exception::
275
276   >>> try:
277   ...     raise NameError('HiThere')
278   ... except NameError:
279   ...     print('An exception flew by!')
280   ...     raise
281   ...
282   An exception flew by!
283   Traceback (most recent call last):
284     File "<stdin>", line 2, in <module>
285       raise NameError('HiThere')
286   NameError: HiThere
287
288
289.. _tut-exception-chaining:
290
291Exception Chaining
292==================
293
294If an unhandled exception occurs inside an :keyword:`except` section, it will
295have the exception being handled attached to it and included in the error
296message::
297
298    >>> try:
299    ...     open("database.sqlite")
300    ... except OSError:
301    ...     raise RuntimeError("unable to handle error")
302    ...
303    Traceback (most recent call last):
304      File "<stdin>", line 2, in <module>
305        open("database.sqlite")
306        ~~~~^^^^^^^^^^^^^^^^^^^
307    FileNotFoundError: [Errno 2] No such file or directory: 'database.sqlite'
308    <BLANKLINE>
309    During handling of the above exception, another exception occurred:
310    <BLANKLINE>
311    Traceback (most recent call last):
312      File "<stdin>", line 4, in <module>
313        raise RuntimeError("unable to handle error")
314    RuntimeError: unable to handle error
315
316To indicate that an exception is a direct consequence of another, the
317:keyword:`raise` statement allows an optional :keyword:`from<raise>` clause::
318
319    # exc must be exception instance or None.
320    raise RuntimeError from exc
321
322This can be useful when you are transforming exceptions. For example::
323
324    >>> def func():
325    ...     raise ConnectionError
326    ...
327    >>> try:
328    ...     func()
329    ... except ConnectionError as exc:
330    ...     raise RuntimeError('Failed to open database') from exc
331    ...
332    Traceback (most recent call last):
333      File "<stdin>", line 2, in <module>
334        func()
335        ~~~~^^
336      File "<stdin>", line 2, in func
337    ConnectionError
338    <BLANKLINE>
339    The above exception was the direct cause of the following exception:
340    <BLANKLINE>
341    Traceback (most recent call last):
342      File "<stdin>", line 4, in <module>
343        raise RuntimeError('Failed to open database') from exc
344    RuntimeError: Failed to open database
345
346It also allows disabling automatic exception chaining using the ``from None``
347idiom::
348
349    >>> try:
350    ...     open('database.sqlite')
351    ... except OSError:
352    ...     raise RuntimeError from None
353    ...
354    Traceback (most recent call last):
355      File "<stdin>", line 4, in <module>
356        raise RuntimeError from None
357    RuntimeError
358
359For more information about chaining mechanics, see :ref:`bltin-exceptions`.
360
361
362.. _tut-userexceptions:
363
364User-defined Exceptions
365=======================
366
367Programs may name their own exceptions by creating a new exception class (see
368:ref:`tut-classes` for more about Python classes).  Exceptions should typically
369be derived from the :exc:`Exception` class, either directly or indirectly.
370
371Exception classes can be defined which do anything any other class can do, but
372are usually kept simple, often only offering a number of attributes that allow
373information about the error to be extracted by handlers for the exception.
374
375Most exceptions are defined with names that end in "Error", similar to the
376naming of the standard exceptions.
377
378Many standard modules define their own exceptions to report errors that may
379occur in functions they define.
380
381
382.. _tut-cleanup:
383
384Defining Clean-up Actions
385=========================
386
387The :keyword:`try` statement has another optional clause which is intended to
388define clean-up actions that must be executed under all circumstances.  For
389example::
390
391   >>> try:
392   ...     raise KeyboardInterrupt
393   ... finally:
394   ...     print('Goodbye, world!')
395   ...
396   Goodbye, world!
397   Traceback (most recent call last):
398     File "<stdin>", line 2, in <module>
399       raise KeyboardInterrupt
400   KeyboardInterrupt
401
402If a :keyword:`finally` clause is present, the :keyword:`!finally`
403clause will execute as the last task before the :keyword:`try`
404statement completes. The :keyword:`!finally` clause runs whether or
405not the :keyword:`!try` statement produces an exception. The following
406points discuss more complex cases when an exception occurs:
407
408* If an exception occurs during execution of the :keyword:`!try`
409  clause, the exception may be handled by an :keyword:`except`
410  clause. If the exception is not handled by an :keyword:`!except`
411  clause, the exception is re-raised after the :keyword:`!finally`
412  clause has been executed.
413
414* An exception could occur during execution of an :keyword:`!except`
415  or :keyword:`!else` clause. Again, the exception is re-raised after
416  the :keyword:`!finally` clause has been executed.
417
418* If the :keyword:`!finally` clause executes a :keyword:`break`,
419  :keyword:`continue` or :keyword:`return` statement, exceptions are not
420  re-raised.
421
422* If the :keyword:`!try` statement reaches a :keyword:`break`,
423  :keyword:`continue` or :keyword:`return` statement, the
424  :keyword:`!finally` clause will execute just prior to the
425  :keyword:`!break`, :keyword:`!continue` or :keyword:`!return`
426  statement's execution.
427
428* If a :keyword:`!finally` clause includes a :keyword:`!return`
429  statement, the returned value will be the one from the
430  :keyword:`!finally` clause's :keyword:`!return` statement, not the
431  value from the :keyword:`!try` clause's :keyword:`!return`
432  statement.
433
434For example::
435
436   >>> def bool_return():
437   ...     try:
438   ...         return True
439   ...     finally:
440   ...         return False
441   ...
442   >>> bool_return()
443   False
444
445A more complicated example::
446
447   >>> def divide(x, y):
448   ...     try:
449   ...         result = x / y
450   ...     except ZeroDivisionError:
451   ...         print("division by zero!")
452   ...     else:
453   ...         print("result is", result)
454   ...     finally:
455   ...         print("executing finally clause")
456   ...
457   >>> divide(2, 1)
458   result is 2.0
459   executing finally clause
460   >>> divide(2, 0)
461   division by zero!
462   executing finally clause
463   >>> divide("2", "1")
464   executing finally clause
465   Traceback (most recent call last):
466     File "<stdin>", line 1, in <module>
467       divide("2", "1")
468       ~~~~~~^^^^^^^^^^
469     File "<stdin>", line 3, in divide
470       result = x / y
471                ~~^~~
472   TypeError: unsupported operand type(s) for /: 'str' and 'str'
473
474As you can see, the :keyword:`finally` clause is executed in any event.  The
475:exc:`TypeError` raised by dividing two strings is not handled by the
476:keyword:`except` clause and therefore re-raised after the :keyword:`!finally`
477clause has been executed.
478
479In real world applications, the :keyword:`finally` clause is useful for
480releasing external resources (such as files or network connections), regardless
481of whether the use of the resource was successful.
482
483
484.. _tut-cleanup-with:
485
486Predefined Clean-up Actions
487===========================
488
489Some objects define standard clean-up actions to be undertaken when the object
490is no longer needed, regardless of whether or not the operation using the object
491succeeded or failed. Look at the following example, which tries to open a file
492and print its contents to the screen. ::
493
494   for line in open("myfile.txt"):
495       print(line, end="")
496
497The problem with this code is that it leaves the file open for an indeterminate
498amount of time after this part of the code has finished executing.
499This is not an issue in simple scripts, but can be a problem for larger
500applications. The :keyword:`with` statement allows objects like files to be
501used in a way that ensures they are always cleaned up promptly and correctly. ::
502
503   with open("myfile.txt") as f:
504       for line in f:
505           print(line, end="")
506
507After the statement is executed, the file *f* is always closed, even if a
508problem was encountered while processing the lines. Objects which, like files,
509provide predefined clean-up actions will indicate this in their documentation.
510
511
512.. _tut-exception-groups:
513
514Raising and Handling Multiple Unrelated Exceptions
515==================================================
516
517There are situations where it is necessary to report several exceptions that
518have occurred. This is often the case in concurrency frameworks, when several
519tasks may have failed in parallel, but there are also other use cases where
520it is desirable to continue execution and collect multiple errors rather than
521raise the first exception.
522
523The builtin :exc:`ExceptionGroup` wraps a list of exception instances so
524that they can be raised together. It is an exception itself, so it can be
525caught like any other exception. ::
526
527   >>> def f():
528   ...     excs = [OSError('error 1'), SystemError('error 2')]
529   ...     raise ExceptionGroup('there were problems', excs)
530   ...
531   >>> f()
532     + Exception Group Traceback (most recent call last):
533     |   File "<stdin>", line 1, in <module>
534     |     f()
535     |     ~^^
536     |   File "<stdin>", line 3, in f
537     |     raise ExceptionGroup('there were problems', excs)
538     | ExceptionGroup: there were problems (2 sub-exceptions)
539     +-+---------------- 1 ----------------
540       | OSError: error 1
541       +---------------- 2 ----------------
542       | SystemError: error 2
543       +------------------------------------
544   >>> try:
545   ...     f()
546   ... except Exception as e:
547   ...     print(f'caught {type(e)}: e')
548   ...
549   caught <class 'ExceptionGroup'>: e
550   >>>
551
552By using ``except*`` instead of ``except``, we can selectively
553handle only the exceptions in the group that match a certain
554type. In the following example, which shows a nested exception
555group, each ``except*`` clause extracts from the group exceptions
556of a certain type while letting all other exceptions propagate to
557other clauses and eventually to be reraised. ::
558
559   >>> def f():
560   ...     raise ExceptionGroup(
561   ...         "group1",
562   ...         [
563   ...             OSError(1),
564   ...             SystemError(2),
565   ...             ExceptionGroup(
566   ...                 "group2",
567   ...                 [
568   ...                     OSError(3),
569   ...                     RecursionError(4)
570   ...                 ]
571   ...             )
572   ...         ]
573   ...     )
574   ...
575   >>> try:
576   ...     f()
577   ... except* OSError as e:
578   ...     print("There were OSErrors")
579   ... except* SystemError as e:
580   ...     print("There were SystemErrors")
581   ...
582   There were OSErrors
583   There were SystemErrors
584     + Exception Group Traceback (most recent call last):
585     |   File "<stdin>", line 2, in <module>
586     |     f()
587     |     ~^^
588     |   File "<stdin>", line 2, in f
589     |     raise ExceptionGroup(
590     |     ...<12 lines>...
591     |     )
592     | ExceptionGroup: group1 (1 sub-exception)
593     +-+---------------- 1 ----------------
594       | ExceptionGroup: group2 (1 sub-exception)
595       +-+---------------- 1 ----------------
596         | RecursionError: 4
597         +------------------------------------
598   >>>
599
600Note that the exceptions nested in an exception group must be instances,
601not types. This is because in practice the exceptions would typically
602be ones that have already been raised and caught by the program, along
603the following pattern::
604
605   >>> excs = []
606   ... for test in tests:
607   ...     try:
608   ...         test.run()
609   ...     except Exception as e:
610   ...         excs.append(e)
611   ...
612   >>> if excs:
613   ...    raise ExceptionGroup("Test Failures", excs)
614   ...
615
616
617.. _tut-exception-notes:
618
619Enriching Exceptions with Notes
620===============================
621
622When an exception is created in order to be raised, it is usually initialized
623with information that describes the error that has occurred. There are cases
624where it is useful to add information after the exception was caught. For this
625purpose, exceptions have a method ``add_note(note)`` that accepts a string and
626adds it to the exception's notes list. The standard traceback rendering
627includes all notes, in the order they were added, after the exception. ::
628
629   >>> try:
630   ...     raise TypeError('bad type')
631   ... except Exception as e:
632   ...     e.add_note('Add some information')
633   ...     e.add_note('Add some more information')
634   ...     raise
635   ...
636   Traceback (most recent call last):
637     File "<stdin>", line 2, in <module>
638       raise TypeError('bad type')
639   TypeError: bad type
640   Add some information
641   Add some more information
642   >>>
643
644For example, when collecting exceptions into an exception group, we may want
645to add context information for the individual errors. In the following each
646exception in the group has a note indicating when this error has occurred. ::
647
648   >>> def f():
649   ...     raise OSError('operation failed')
650   ...
651   >>> excs = []
652   >>> for i in range(3):
653   ...     try:
654   ...         f()
655   ...     except Exception as e:
656   ...         e.add_note(f'Happened in Iteration {i+1}')
657   ...         excs.append(e)
658   ...
659   >>> raise ExceptionGroup('We have some problems', excs)
660     + Exception Group Traceback (most recent call last):
661     |   File "<stdin>", line 1, in <module>
662     |     raise ExceptionGroup('We have some problems', excs)
663     | ExceptionGroup: We have some problems (3 sub-exceptions)
664     +-+---------------- 1 ----------------
665       | Traceback (most recent call last):
666       |   File "<stdin>", line 3, in <module>
667       |     f()
668       |     ~^^
669       |   File "<stdin>", line 2, in f
670       |     raise OSError('operation failed')
671       | OSError: operation failed
672       | Happened in Iteration 1
673       +---------------- 2 ----------------
674       | Traceback (most recent call last):
675       |   File "<stdin>", line 3, in <module>
676       |     f()
677       |     ~^^
678       |   File "<stdin>", line 2, in f
679       |     raise OSError('operation failed')
680       | OSError: operation failed
681       | Happened in Iteration 2
682       +---------------- 3 ----------------
683       | Traceback (most recent call last):
684       |   File "<stdin>", line 3, in <module>
685       |     f()
686       |     ~^^
687       |   File "<stdin>", line 2, in f
688       |     raise OSError('operation failed')
689       | OSError: operation failed
690       | Happened in Iteration 3
691       +------------------------------------
692   >>>
693