Repository navigation
Expand file tree
/
Copy pathpep-0654.rst
More file actions
1507 lines (1232 loc) · 59.6 KB
/
Copy pathpep-0654.rst
File metadata and controls
1507 lines (1232 loc) · 59.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
PEP: 654
Title: Exception Groups and except*
Author: Irit Katriel <irit@python.org>,
Yury Selivanov <yury@edgedb.com>,
Guido van Rossum <guido@python.org>
Discussions-To: https://discuss.python.org/t/accepting-pep-654-exception-groups-and-except/10813
Status: Final
Type: Standards Track
Created: 22-Feb-2021
Python-Version: 3.11
Post-History: `22-Feb-2021 <https://mail.python.org/archives/list/python-dev@python.org/thread/L5Q27DVKOKZCDNCAWRIQVOZ5DZCZHLRM/>`__,
`20-Mar-2021 <https://mail.python.org/archives/list/python-dev@python.org/thread/MQ2UCSQ2ZC4FIGT7KSVI6BJA4FCXSOCL/>`__,
`03-Oct-2021 <https://mail.python.org/archives/list/python-dev@python.org/thread/4B256YKUPW5P2M44GG5H6FBL3PSV6ODP/>`__,
Resolution: https://discuss.python.org/t/accepting-pep-654-exception-groups-and-except/10813/1
.. canonical-doc:: :ref:`python:lib-exception-groups` and :ref:`python:except_star`
See :ref:`python:tut-exception-groups` for a user-focused tutorial.
Abstract
========
This document proposes language extensions that allow programs to raise and handle
multiple unrelated exceptions simultaneously:
* A new standard exception type, the ``ExceptionGroup``, which represents a
group of unrelated exceptions being propagated together.
* A new syntax ``except*`` for handling ``ExceptionGroups``.
Motivation
==========
The interpreter is currently able to propagate at most one exception at a
time. The chaining features introduced in :pep:`3134` link together
exceptions that are related to each other as the cause or context, but
there are situations where multiple unrelated exceptions need to be propagated
together as the stack unwinds. Several real world use cases are listed below.
* **Concurrent errors**. Libraries for async concurrency provide APIs to invoke
multiple tasks and return their results in aggregate. There isn't currently
a good way for such libraries to handle situations where multiple tasks
raise exceptions. The Python standard library's ``asyncio.gather()`` [1]_
function provides two options: raise the first exception, or return the
exceptions in the results list. The Trio [2]_
library has a ``MultiError`` exception type which it raises to report a
collection of errors. Work on this PEP was initially motivated by the
difficulties in handling ``MultiErrors`` [9]_, which are detailed in a design
document for an improved version, ``MultiError2`` [3]_.
That document demonstrates how difficult it is to create an effective API
for reporting and handling multiple errors without the language changes we
are proposing (see also the `Programming Without 'except \*'`_ section.)
Implementing a better task spawning API in asyncio, inspired by Trio
nurseries [13]_, was the main motivation for this PEP. That work is currently
blocked on Python not having native language level support for exception
groups.
* **Multiple failures when retrying an operation.** The Python standard
library's ``socket.create_connection`` function may attempt to connect to
different addresses, and if all attempts fail it needs to report that to the
user. It is an open issue how to aggregate these errors, particularly when
they are different (see issue 29980 [4]_.)
* **Multiple user callbacks fail.** Python's ``atexit.register()`` function
allows users to register functions that are called on system exit. If any of
them raise exceptions, only the last one is reraised, but it would be better
to reraise all of them together (see ``atexit`` documentation [5]_.)
Similarly, the pytest library allows users to register finalizers which
are executed at teardown. If more than one of these finalizers raises an
exception, only the first is reported to the user. This can be improved with
``ExceptionGroups``, as explained in this issue by pytest developer Ran Benita
(see pytest issue 8217 [6]_.)
* **Multiple errors in a complex calculation.** The Hypothesis library performs
automatic bug reduction (simplifying code that demonstrates a bug). In the
process it may find variations that generate different errors, and
(optionally) reports all of them (see the Hypothesis documentation [7]_.)
An ``ExceptionGroup`` mechanism as we are proposing here can resolve some of
the difficulties with debugging that are mentioned in the link above, and
which are due to the loss of context/cause information (communicated
by Hypothesis Core Developer Zac Hatfield-Dodds).
* **Errors in wrapper code.** The Python standard library's
``tempfile.TemporaryDirectory`` context manager
had an issue where an exception raised during cleanup in ``__exit__``
effectively masked an exception that the user's code raised inside the context
manager scope. While the user's exception was chained as the context of the
cleanup error, it was not caught by the user's except clause
(see issue 40857 [8]_.)
The issue was resolved by making the cleanup code ignore errors, thus
sidestepping the multiple exception problem. With the features we propose
here, it would be possible for ``__exit__`` to raise an ``ExceptionGroup``
containing its own errors along with the user's errors, and this would allow
the user to catch their own exceptions by their types.
Rationale
=========
Grouping several exceptions together can be done without changes to the
language, simply by creating a container exception type.
Trio [2]_ is an example of a library that has made use of this technique in its
``MultiError`` [9]_ type. However, such an approach requires calling code to catch
the container exception type, and then to inspect it to determine the types of
errors that had occurred, extract the ones it wants to handle, and reraise the
rest. Furthermore, exceptions in Python have important information attached to
their ``__traceback__``, ``__cause__`` and ``__context__`` fields, and
designing a container type that preserves the integrity of this information
requires care; it is not as simple as collecting exceptions into a set.
Changes to the language are required in order to extend support for
exception groups in the style of existing exception handling mechanisms. At
the very least we would like to be able to catch an exception group only if
it contains an exception of a type that we choose to handle. Exceptions of
other types in the same group need to be automatically reraised,
otherwise it is too easy for user code to inadvertently swallow exceptions
that it is not handling.
We considered whether it is possible to modify the semantics of ``except``
for this purpose, in a backwards-compatible manner, and found that it is not.
See the `Rejected Ideas`_ section for more on this.
The purpose of this PEP, then, is to add the ``ExceptionGroup`` builtin type
and the ``except*`` syntax for handling exception groups in the interpreter.
The desired semantics of ``except*`` are sufficiently different from the
current exception handling semantics that we are not proposing to modify the
behavior of the ``except`` keyword but rather to add the new ``except*``
syntax.
Our premise is that exception groups and ``except*`` will be used
selectively, only when they are needed. We do not expect them to become
the default mechanism for exception handling. The decision to raise
exception groups from a library needs to be considered carefully and
regarded as an API-breaking change. We expect that this will normally be
done by introducing a new API rather than modifying an existing one.
Specification
=============
ExceptionGroup and BaseExceptionGroup
-------------------------------------
We propose to add two new builtin exception types:
``BaseExceptionGroup(BaseException)`` and
``ExceptionGroup(BaseExceptionGroup, Exception)``. They are assignable to
``Exception.__cause__`` and ``Exception.__context__``, and they can be
raised and handled as any exception with ``raise ExceptionGroup(...)`` and
``try: ... except ExceptionGroup: ...`` or ``raise BaseExceptionGroup(...)``
and ``try: ... except BaseExceptionGroup: ...``.
Both have a constructor that takes two positional-only arguments: a message
string and a sequence of the nested exceptions, which are exposed in the
fields ``message`` and ``exceptions``. For example:
``ExceptionGroup('issues', [ValueError('bad value'), TypeError('bad type')])``.
The difference between them is that ``ExceptionGroup`` can only wrap
``Exception`` subclasses while ``BaseExceptionGroup`` can wrap any
``BaseException`` subclass. The ``BaseExceptionGroup`` constructor
inspects the nested exceptions and if they are all ``Exception`` subclasses,
it returns an ``ExceptionGroup`` rather than a ``BaseExceptionGroup``. The
``ExceptionGroup`` constructor raises a ``TypeError`` if any of the nested
exceptions is not an ``Exception`` instance. In the rest of the document,
when we refer to an exception group, we mean either an ``ExceptionGroup``
or a ``BaseExceptionGroup``. When it is necessary to make the distinction,
we use the class name. For brevity, we will use ``ExceptionGroup`` in code
examples that are relevant to both.
Since an exception group can be nested, it represents a tree of exceptions,
where the leaves are plain exceptions and each internal node represents a time
at which the program grouped some unrelated exceptions into a new group and
raised them together.
The ``BaseExceptionGroup.subgroup(condition)`` method gives us a way to obtain
an exception group that has the same metadata (message, cause, context,
traceback) as the original group, and the same nested structure of groups, but
contains only those exceptions for which the condition is true:
.. code-block::
>>> eg = ExceptionGroup(
... "one",
... [
... TypeError(1),
... ExceptionGroup(
... "two",
... [TypeError(2), ValueError(3)]
... ),
... ExceptionGroup(
... "three",
... [OSError(4)]
... )
... ]
... )
>>> import traceback
>>> traceback.print_exception(eg)
| ExceptionGroup: one (3 sub-exceptions)
+-+---------------- 1 ----------------
| TypeError: 1
+---------------- 2 ----------------
| ExceptionGroup: two (2 sub-exceptions)
+-+---------------- 1 ----------------
| TypeError: 2
+---------------- 2 ----------------
| ValueError: 3
+------------------------------------
+---------------- 3 ----------------
| ExceptionGroup: three (1 sub-exception)
+-+---------------- 1 ----------------
| OSError: 4
+------------------------------------
>>> type_errors = eg.subgroup(lambda e: isinstance(e, TypeError))
>>> traceback.print_exception(type_errors)
| ExceptionGroup: one (2 sub-exceptions)
+-+---------------- 1 ----------------
| TypeError: 1
+---------------- 2 ----------------
| ExceptionGroup: two (1 sub-exception)
+-+---------------- 1 ----------------
| TypeError: 2
+------------------------------------
>>>
The match condition is also applied to interior nodes (the exception
groups), and a match causes the whole subtree rooted at this node
to be included in the result.
Empty nested groups are omitted from the result, as in the
case of ``ExceptionGroup("three")`` in the example above. If none of the
exceptions match the condition, ``subgroup`` returns ``None`` rather
than an empty group. The original ``eg``
is unchanged by ``subgroup``, but the value returned is not necessarily a full
new copy. Leaf exceptions are not copied, nor are exception groups which are
fully contained in the result. When it is necessary to partition a
group because the condition holds for some, but not all of its
contained exceptions, a new ``ExceptionGroup`` or ``BaseExceptionGroup``
instance is created, while the ``__cause__``, ``__context__`` and
``__traceback__`` fields are copied by reference, so they are shared with
the original ``eg``.
If both the subgroup and its complement are needed, the
``BaseExceptionGroup.split(condition)`` method can be used:
.. code-block::
>>> type_errors, other_errors = eg.split(lambda e: isinstance(e, TypeError))
>>> traceback.print_exception(type_errors)
| ExceptionGroup: one (2 sub-exceptions)
+-+---------------- 1 ----------------
| TypeError: 1
+---------------- 2 ----------------
| ExceptionGroup: two (1 sub-exception)
+-+---------------- 1 ----------------
| TypeError: 2
+------------------------------------
>>> traceback.print_exception(other_errors)
| ExceptionGroup: one (2 sub-exceptions)
+-+---------------- 1 ----------------
| ExceptionGroup: two (1 sub-exception)
+-+---------------- 1 ----------------
| ValueError: 3
+------------------------------------
+---------------- 2 ----------------
| ExceptionGroup: three (1 sub-exception)
+-+---------------- 1 ----------------
| OSError: 4
+------------------------------------
>>>
If a split is trivial (one side is empty), then None is returned for the
other side:
.. code-block::
>>> other_errors.split(lambda e: isinstance(e, SyntaxError))
(None, ExceptionGroup('one', [
ExceptionGroup('two', [
ValueError(3)
]),
ExceptionGroup('three', [
OSError(4)])]))
Since splitting by exception type is a very common use case, ``subgroup`` and
``split`` can take an exception type or tuple of exception types and treat it
as a shorthand for matching that type: ``eg.split(T)`` divides ``eg`` into the
subgroup of leaf exceptions that match the type ``T``, and the subgroup of those
that do not (using the same check as ``except`` for a match).
Subclassing Exception Groups
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It is possible to subclass exception groups, but when doing that it is
usually necessary to specify how ``subgroup()`` and ``split()`` should
create new instances for the matching or non-matching part of the partition.
``BaseExceptionGroup`` exposes an instance method ``derive(self, excs)``
which is called whenever ``subgroup`` and ``split`` need to create a new
exception group. The parameter ``excs`` is the sequence of exceptions to
include in the new group. Since ``derive`` has access to self, it can
copy data from it to the new object. For example, if we need an exception
group subclass that has an additional error code field, we can do this:
.. code-block::
class MyExceptionGroup(ExceptionGroup):
def __new__(cls, message, excs, errcode):
obj = super().__new__(cls, message, excs)
obj.errcode = errcode
return obj
def derive(self, excs):
return MyExceptionGroup(self.message, excs, self.errcode)
Note that we override ``__new__`` rather than ``__init__``; this is because
``BaseExceptionGroup.__new__`` needs to inspect the constructor arguments, and
its signature is different from that of the subclass. Note also that our
``derive`` function does not copy the ``__context__``, ``__cause__`` and
``__traceback__`` fields, because ``subgroup`` and ``split`` do that for us.
With the class defined above, we have the following:
.. code-block::
>>> eg = MyExceptionGroup("eg", [TypeError(1), ValueError(2)], 42)
>>>
>>> match, rest = eg.split(ValueError)
>>> print(f'match: {match!r}: {match.errcode}')
match: MyExceptionGroup('eg', [ValueError(2)], 42): 42
>>> print(f'rest: {rest!r}: {rest.errcode}')
rest: MyExceptionGroup('eg', [TypeError(1)], 42): 42
>>>
If we do not override ``derive``, then split calls the one defined
on ``BaseExceptionGroup``, which returns an instance of ``ExceptionGroup``
if all contained exceptions are of type ``Exception``, and
``BaseExceptionGroup`` otherwise. For example:
.. code-block::
>>> class MyExceptionGroup(BaseExceptionGroup):
... pass
...
>>> eg = MyExceptionGroup("eg", [ValueError(1), KeyboardInterrupt(2)])
>>> match, rest = eg.split(ValueError)
>>> print(f'match: {match!r}')
match: ExceptionGroup('eg', [ValueError(1)])
>>> print(f'rest: {rest!r}')
rest: BaseExceptionGroup('eg', [KeyboardInterrupt(2)])
>>>
The Traceback of an Exception Group
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For regular exceptions, the traceback represents a simple path of frames,
from the frame in which the exception was raised to the frame in which it
was caught or, if it hasn't been caught yet, the frame that the program's
execution is currently in. The list is constructed by the interpreter, which
appends any frame from which it exits to the traceback of the 'current
exception' if one exists. To support efficient appends, the links in a
traceback's list of frames are from the oldest to the newest frame. Appending
a new frame is then simply a matter of inserting a new head to the linked
list referenced from the exception's ``__traceback__`` field. Crucially, the
traceback's frame list is immutable in the sense that frames only need to be
added at the head, and never need to be removed.
We do not need to make any changes to this data structure. The ``__traceback__``
field of the exception group instance represents the path that the contained
exceptions travelled through together after being joined into the
group, and the same field on each of the nested exceptions
represents the path through which this exception arrived at the frame of the
merge.
What we do need to change is any code that interprets and displays tracebacks,
because it now needs to continue into tracebacks of nested exceptions, as
in the following example:
.. code-block::
>>> def f(v):
... try:
... raise ValueError(v)
... except ValueError as e:
... return e
...
>>> try:
... raise ExceptionGroup("one", [f(1)])
... except ExceptionGroup as e:
... eg = e
...
>>> raise ExceptionGroup("two", [f(2), eg])
+ Exception Group Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
| ExceptionGroup: two (2 sub-exceptions)
+-+---------------- 1 ----------------
| Traceback (most recent call last):
| File "<stdin>", line 3, in f
| ValueError: 2
+---------------- 2 ----------------
| Exception Group Traceback (most recent call last):
| File "<stdin>", line 2, in <module>
| ExceptionGroup: one (1 sub-exception)
+-+---------------- 1 ----------------
| Traceback (most recent call last):
| File "<stdin>", line 3, in f
| ValueError: 1
+------------------------------------
>>>
Handling Exception Groups
~~~~~~~~~~~~~~~~~~~~~~~~~
We expect that when programs catch and handle exception groups, they will
typically either query to check if it has leaf exceptions for which some
condition holds (using ``subgroup`` or ``split``) or format the exception
(using the ``traceback`` module's methods).
It is less likely to be useful to iterate over the individual leaf exceptions.
To see why, suppose that an application caught an exception group raised by
an ``asyncio.gather()`` call. At this stage, the context for each specific
exception is lost. Any recovery for this exception should have been performed
before it was grouped with other exceptions [10]_.
Furthermore, the application is likely to react in the same way to any number
of instances of a certain exception type, so it is more likely that we will
want to know whether ``eg.subgroup(T)`` is None or not, than we are to be
interested in the number of ``Ts`` in ``eg``.
However, there are situations where it is necessary to inspect the
individual leaf exceptions. For example, suppose that we have an
exception group ``eg`` and that we want to log the ``OSErrors`` that have a
specific error code and reraise everything else. We can do this by passing
a function with side effects to ``subgroup``, as follows:
.. code-block::
def log_and_ignore_ENOENT(err):
if isinstance(err, OSError) and err.errno == ENOENT:
log(err)
return False
else:
return True
try:
. . .
except ExceptionGroup as eg:
eg = eg.subgroup(log_and_ignore_ENOENT)
if eg is not None:
raise eg
In the previous example, when ``log_and_ignore_ENOENT`` is invoked on a leaf
exception, only part of this exception's traceback is accessible -- the part
referenced from its ``__traceback__`` field. If we need the full traceback,
we need to look at the concatenation of the tracebacks of the exceptions on
the path from the root to this leaf. We can get that with direct iteration,
recursively, as follows:
.. code-block::
def leaf_generator(exc, tbs=None):
if tbs is None:
tbs = []
tbs.append(exc.__traceback__)
if isinstance(exc, BaseExceptionGroup):
for e in exc.exceptions:
yield from leaf_generator(e, tbs)
else:
# exc is a leaf exception and its traceback
# is the concatenation of the traceback
# segments in tbs.
# Note: the list returned (tbs) is reused in each iteration
# through the generator. Make a copy if your use case holds
# on to it beyond the current iteration or mutates its contents.
yield exc, tbs
tbs.pop()
We can then process the full tracebacks of the leaf exceptions:
.. code-block::
>>> import traceback
>>>
>>> def g(v):
... try:
... raise ValueError(v)
... except Exception as e:
... return e
...
>>> def f():
... raise ExceptionGroup("eg", [g(1), g(2)])
...
>>> try:
... f()
... except BaseException as e:
... eg = e
...
>>> for (i, (exc, tbs)) in enumerate(leaf_generator(eg)):
... print(f"\n=== Exception #{i+1}:")
... traceback.print_exception(exc)
... print(f"The complete traceback for Exception #{i+1}:")
... for tb in tbs:
... traceback.print_tb(tb)
...
=== Exception #1:
Traceback (most recent call last):
File "<stdin>", line 3, in g
ValueError: 1
The complete traceback for Exception #1
File "<stdin>", line 2, in <module>
File "<stdin>", line 2, in f
File "<stdin>", line 3, in g
=== Exception #2:
Traceback (most recent call last):
File "<stdin>", line 3, in g
ValueError: 2
The complete traceback for Exception #2:
File "<stdin>", line 2, in <module>
File "<stdin>", line 2, in f
File "<stdin>", line 3, in g
>>>
except*
-------
We are proposing to introduce a new variant of the ``try..except`` syntax to
simplify working with exception groups. The ``*`` symbol indicates that multiple
exceptions can be handled by each ``except*`` clause:
.. code-block::
try:
...
except* SpamError:
...
except* FooError as e:
...
except* (BarError, BazError) as e:
...
In a traditional ``try-except`` statement there is only one exception to handle,
so the body of at most one ``except`` clause executes; the first one that matches
the exception. With the new syntax, an ``except*`` clause can match a subgroup
of the exception group that was raised, while the remaining part is matched
by following ``except*`` clauses. In other words, a single exception group can
cause several ``except*`` clauses to execute, but each such clause executes at
most once (for all matching exceptions from the group) and each exception is
either handled by exactly one clause (the first one that matches its type)
or is reraised at the end. The manner in which each exception is handled by
a ``try-except*`` block is independent of any other exceptions in the group.
For example, suppose that the body of the ``try`` block above raises
``eg = ExceptionGroup('msg', [FooError(1), FooError(2), BazError()])``.
The ``except*`` clauses are evaluated in order by calling ``split`` on the
``unhandled`` exception group, which is initially equal to ``eg`` and then shrinks
as exceptions are matched and extracted from it. In the first ``except*`` clause,
``unhandled.split(SpamError)`` returns ``(None, unhandled)`` so the body of this
block is not executed and ``unhandled`` is unchanged. For the second block,
``unhandled.split(FooError)`` returns a non-trivial split ``(match, rest)`` with
``match = ExceptionGroup('msg', [FooError(1), FooError(2)])``
and ``rest = ExceptionGroup('msg', [BazError()])``. The body of this ``except*``
block is executed, with the value of ``e`` and ``sys.exc_info()`` set to ``match``.
Then, ``unhandled`` is set to ``rest``.
Finally, the third block matches the remaining exception so it is executed
with ``e`` and ``sys.exc_info()`` set to ``ExceptionGroup('msg', [BazError()])``.
Exceptions are matched using a subclass check. For example:
.. code-block::
try:
low_level_os_operation()
except* OSError as eg:
for e in eg.exceptions:
print(type(e).__name__)
could output:
.. code-block::
BlockingIOError
ConnectionRefusedError
OSError
InterruptedError
BlockingIOError
The order of ``except*`` clauses is significant just like with the regular
``try..except``:
.. code-block::
>>> try:
... raise ExceptionGroup("problem", [BlockingIOError()])
... except* OSError as e: # Would catch the error
... print(repr(e))
... except* BlockingIOError: # Would never run
... print('never')
...
ExceptionGroup('problem', [BlockingIOError()])
Recursive Matching
~~~~~~~~~~~~~~~~~~
The matching of ``except*`` clauses against an exception group is performed
recursively, using the ``split()`` method:
.. code-block::
>>> try:
... raise ExceptionGroup(
... "eg",
... [
... ValueError('a'),
... TypeError('b'),
... ExceptionGroup(
... "nested",
... [TypeError('c'), KeyError('d')])
... ]
... )
... except* TypeError as e1:
... print(f'e1 = {e1!r}')
... except* Exception as e2:
... print(f'e2 = {e2!r}')
...
e1 = ExceptionGroup('eg', [TypeError('b'), ExceptionGroup('nested', [TypeError('c')])])
e2 = ExceptionGroup('eg', [ValueError('a'), ExceptionGroup('nested', [KeyError('d')])])
>>>
Unmatched Exceptions
~~~~~~~~~~~~~~~~~~~~
If not all exceptions in an exception group were matched by the ``except*``
clauses, the remaining part of the group is propagated on:
.. code-block::
>>> try:
... try:
... raise ExceptionGroup(
... "msg", [
... ValueError('a'), TypeError('b'),
... TypeError('c'), KeyError('e')
... ]
... )
... except* ValueError as e:
... print(f'got some ValueErrors: {e!r}')
... except* TypeError as e:
... print(f'got some TypeErrors: {e!r}')
... except ExceptionGroup as e:
... print(f'propagated: {e!r}')
...
got some ValueErrors: ExceptionGroup('msg', [ValueError('a')])
got some TypeErrors: ExceptionGroup('msg', [TypeError('b'), TypeError('c')])
propagated: ExceptionGroup('msg', [KeyError('e')])
>>>
Naked Exceptions
~~~~~~~~~~~~~~~~
If the exception raised inside the ``try`` body is not of type ``ExceptionGroup``
or ``BaseExceptionGroup``, we call it a ``naked`` exception. If its type matches
one of the ``except*`` clauses, it is caught and wrapped by an ``ExceptionGroup``
(or ``BaseExceptionGroup`` if it is not an ``Exception`` subclass) with an empty
message string. This is to make the type of ``e`` consistent and statically known:
.. code-block::
>>> try:
... raise BlockingIOError
... except* OSError as e:
... print(repr(e))
...
ExceptionGroup('', [BlockingIOError()])
However, if a naked exception is not caught, it propagates in its original
naked form:
.. code-block::
>>> try:
... try:
... raise ValueError(12)
... except* TypeError as e:
... print('never')
... except ValueError as e:
... print(f'caught ValueError: {e!r}')
...
caught ValueError: ValueError(12)
>>>
Raising exceptions in an ``except*`` block
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In a traditional ``except`` block, there are two ways to raise exceptions:
``raise e`` to explicitly raise an exception object ``e``, or naked ``raise`` to
reraise the 'current exception'. When ``e`` is the current exception, the two
forms are not equivalent because a reraise does not add the current frame to
the stack:
.. code-block::
def foo(): | def foo():
try: | try:
1 / 0 | 1 / 0
except ZeroDivisionError as e: | except ZeroDivisionError:
raise e | raise
|
foo() | foo()
|
Traceback (most recent call last): | Traceback (most recent call last):
File "/Users/guido/a.py", line 7 | File "/Users/guido/b.py", line 7
foo() | foo()
File "/Users/guido/a.py", line 5 | File "/Users/guido/b.py", line 3
raise e | 1/0
File "/Users/guido/a.py", line 3 | ZeroDivisionError: division by zero
1/0 |
ZeroDivisionError: division by zero |
This holds for exception groups as well, but the situation is now more complex
because there can be exceptions raised and reraised from multiple ``except*``
clauses, as well as unhandled exceptions that need to propagate.
The interpreter needs to combine all those exceptions into a result, and
raise that.
The reraised exceptions and the unhandled exceptions are subgroups of the
original group, and share its metadata (cause, context, traceback).
On the other hand, each of the explicitly raised exceptions has its own
metadata - the traceback contains the line from which it was raised, its
cause is whatever it may have been explicitly chained to, and its context is the
value of ``sys.exc_info()`` in the ``except*`` clause of the raise.
In the aggregated exception group, the reraised and unhandled exceptions have
the same relative structure as in the original exception, as if they were split
off together in one ``subgroup`` call. For example, in the snippet below the
inner ``try-except*`` block raises an ``ExceptionGroup`` that contains all
``ValueErrors`` and ``TypeErrors`` merged back into the same shape they had in
the original ``ExceptionGroup``:
.. code-block::
>>> try:
... try:
... raise ExceptionGroup(
... "eg",
... [
... ValueError(1),
... TypeError(2),
... OSError(3),
... ExceptionGroup(
... "nested",
... [OSError(4), TypeError(5), ValueError(6)])
... ]
... )
... except* ValueError as e:
... print(f'*ValueError: {e!r}')
... raise
... except* OSError as e:
... print(f'*OSError: {e!r}')
... except ExceptionGroup as e:
... print(repr(e))
...
*ValueError: ExceptionGroup('eg', [ValueError(1), ExceptionGroup('nested', [ValueError(6)])])
*OSError: ExceptionGroup('eg', [OSError(3), ExceptionGroup('nested', [OSError(4)])])
ExceptionGroup('eg', [ValueError(1), TypeError(2), ExceptionGroup('nested', [TypeError(5), ValueError(6)])])
>>>
When exceptions are raised explicitly, they are independent of the original
exception group, and cannot be merged with it (they have their own cause,
context and traceback). Instead, they are combined into a new ``ExceptionGroup``
(or ``BaseExceptionGroup``), which also contains the reraised/unhandled
subgroup described above.
In the following example, the ``ValueErrors`` were raised so they are in their
own ``ExceptionGroup``, while the ``OSErrors`` were reraised so they were
merged with the unhandled ``TypeErrors``.
.. code-block::
>>> try:
... raise ExceptionGroup(
... "eg",
... [
... ValueError(1),
... TypeError(2),
... OSError(3),
... ExceptionGroup(
... "nested",
... [OSError(4), TypeError(5), ValueError(6)])
... ]
... )
... except* ValueError as e:
... print(f'*ValueError: {e!r}')
... raise e
... except* OSError as e:
... print(f'*OSError: {e!r}')
... raise
...
*ValueError: ExceptionGroup('eg', [ValueError(1), ExceptionGroup('nested', [ValueError(6)])])
*OSError: ExceptionGroup('eg', [OSError(3), ExceptionGroup('nested', [OSError(4)])])
| ExceptionGroup: (2 sub-exceptions)
+-+---------------- 1 ----------------
| Exception Group Traceback (most recent call last):
| File "<stdin>", line 15, in <module>
| File "<stdin>", line 2, in <module>
| ExceptionGroup: eg (2 sub-exceptions)
+-+---------------- 1 ----------------
| ValueError: 1
+---------------- 2 ----------------
| ExceptionGroup: nested (1 sub-exception)
+-+---------------- 1 ----------------
| ValueError: 6
+------------------------------------
+---------------- 2 ----------------
| Exception Group Traceback (most recent call last):
| File "<stdin>", line 2, in <module>
| ExceptionGroup: eg (3 sub-exceptions)
+-+---------------- 1 ----------------
| TypeError: 2
+---------------- 2 ----------------
| OSError: 3
+---------------- 3 ----------------
| ExceptionGroup: nested (2 sub-exceptions)
+-+---------------- 1 ----------------
| OSError: 4
+---------------- 2 ----------------
| TypeError: 5
+------------------------------------
>>>
Chaining
~~~~~~~~
Explicitly raised exception groups are chained as with any exceptions. The
following example shows how part of ``ExceptionGroup`` "one" became the
context for ``ExceptionGroup`` "two", while the other part was combined with
it into the new ``ExceptionGroup``.
.. code-block::
>>> try:
... raise ExceptionGroup("one", [ValueError('a'), TypeError('b')])
... except* ValueError:
... raise ExceptionGroup("two", [KeyError('x'), KeyError('y')])
...
| ExceptionGroup: (2 sub-exceptions)
+-+---------------- 1 ----------------
| Exception Group Traceback (most recent call last):
| File "<stdin>", line 2, in <module>
| ExceptionGroup: one (1 sub-exception)
+-+---------------- 1 ----------------
| ValueError: a
+------------------------------------
|
| During handling of the above exception, another exception occurred:
|
| Exception Group Traceback (most recent call last):
| File "<stdin>", line 4, in <module>
| ExceptionGroup: two (2 sub-exceptions)
+-+---------------- 1 ----------------
| KeyError: 'x'
+---------------- 2 ----------------
| KeyError: 'y'
+------------------------------------
+---------------- 2 ----------------
| Exception Group Traceback (most recent call last):
| File "<stdin>", line 2, in <module>
| ExceptionGroup: one (1 sub-exception)
+-+---------------- 1 ----------------
| TypeError: b
+------------------------------------
>>>
Raising New Exceptions
~~~~~~~~~~~~~~~~~~~~~~
In the previous examples the explicit raises were of the exceptions that
were caught, so for completion we show a new exception being raised, with
chaining:
.. code-block::
>>> try:
... raise TypeError('bad type')
... except* TypeError as e:
... raise ValueError('bad value') from e
...
| ExceptionGroup: (1 sub-exception)
+-+---------------- 1 ----------------
| Traceback (most recent call last):
| File "<stdin>", line 2, in <module>
| TypeError: bad type
+------------------------------------
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
ValueError: bad value
>>>
Note that exceptions raised in one ``except*`` clause are not eligible to match
other clauses from the same ``try`` statement:
.. code-block::
>>> try:
... raise TypeError(1)
... except* TypeError:
... raise ValueError(2) from None # <- not caught in the next clause
... except* ValueError:
... print('never')
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
ValueError: 2
>>>
Raising a new instance of a naked exception does not cause this exception to
be wrapped by an exception group. Rather, the exception is raised as is, and
if it needs to be combined with other propagated exceptions, it becomes a
direct child of the new exception group created for that:
.. code-block::
>>> try:
... raise ExceptionGroup("eg", [ValueError('a')])
... except* ValueError:
... raise KeyError('x')
...
| ExceptionGroup: (1 sub-exception)
+-+---------------- 1 ----------------
| Exception Group Traceback (most recent call last):
| File "<stdin>", line 2, in <module>
| ExceptionGroup: eg (1 sub-exception)
+-+---------------- 1 ----------------
| ValueError: a
+------------------------------------
|
| During handling of the above exception, another exception occurred:
|
| Traceback (most recent call last):
| File "<stdin>", line 4, in <module>
| KeyError: 'x'
+------------------------------------
>>>
>>> try:
... raise ExceptionGroup("eg", [ValueError('a'), TypeError('b')])
... except* ValueError:
... raise KeyError('x')
...
| ExceptionGroup: (2 sub-exceptions)
+-+---------------- 1 ----------------
| Exception Group Traceback (most recent call last):
| File "<stdin>", line 2, in <module>
| ExceptionGroup: eg (1 sub-exception)
+-+---------------- 1 ----------------
| ValueError: a
+------------------------------------
|
| During handling of the above exception, another exception occurred:
|
| Traceback (most recent call last):
| File "<stdin>", line 4, in <module>
| KeyError: 'x'
+---------------- 2 ----------------
| Exception Group Traceback (most recent call last):
| File "<stdin>", line 2, in <module>
| ExceptionGroup: eg (1 sub-exception)
+-+---------------- 1 ----------------
| TypeError: b
+------------------------------------
>>>
Finally, as an example of how the proposed semantics can help us work
effectively with exception groups, the following code ignores all ``EPIPE``
OS errors, while letting all other exceptions propagate.
.. code-block::
try:
low_level_os_operation()