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