@@ -559,3 +559,67 @@ the following pattern::
559
559
... raise ExceptionGroup("Test Failures", excs)
560
560
...
561
561
562
+
563
+ Enriching Exceptions with Notes
564
+ ===============================
565
+
566
+ When an exception is created in order to be raised, it is usually initialized
567
+ with information that describes the error that has occurred. There are cases
568
+ where it is useful to add information after the exception was caught. For this
569
+ purpose, exceptions have a method ``add_note(note) `` that accepts a string and
570
+ adds it to the exception's notes list. The standard traceback rendering
571
+ includes all notes, in the order they were added, after the exception. ::
572
+
573
+ >>> try:
574
+ ... raise TypeError('bad type')
575
+ ... except Exception as e:
576
+ ... e.add_note('Add some information')
577
+ ... e.add_note('Add some more information')
578
+ ... raise
579
+ ...
580
+ Traceback (most recent call last):
581
+ File "<stdin>", line 2, in <module>
582
+ TypeError: bad type
583
+ Add some information
584
+ Add some more information
585
+ >>>
586
+
587
+ For example, when collecting exceptions into an exception group, we may want
588
+ to add context information for the individual errors. In the following each
589
+ exception in the group has a note indicating when this error has occurred. ::
590
+
591
+ >>> def f():
592
+ ... raise OSError('operation failed')
593
+ ...
594
+ >>> excs = []
595
+ >>> for i in range(3):
596
+ ... try:
597
+ ... f()
598
+ ... except Exception as e:
599
+ ... e.add_note(f'Happened in Iteration {i+1}')
600
+ ... excs.append(e)
601
+ ...
602
+ >>> raise ExceptionGroup('We have some problems', excs)
603
+ + Exception Group Traceback (most recent call last):
604
+ | File "<stdin>", line 1, in <module>
605
+ | ExceptionGroup: We have some problems (3 sub-exceptions)
606
+ +-+---------------- 1 ----------------
607
+ | Traceback (most recent call last):
608
+ | File "<stdin>", line 3, in <module>
609
+ | File "<stdin>", line 2, in f
610
+ | OSError: operation failed
611
+ | Happened in Iteration 1
612
+ +---------------- 2 ----------------
613
+ | Traceback (most recent call last):
614
+ | File "<stdin>", line 3, in <module>
615
+ | File "<stdin>", line 2, in f
616
+ | OSError: operation failed
617
+ | Happened in Iteration 2
618
+ +---------------- 3 ----------------
619
+ | Traceback (most recent call last):
620
+ | File "<stdin>", line 3, in <module>
621
+ | File "<stdin>", line 2, in f
622
+ | OSError: operation failed
623
+ | Happened in Iteration 3
624
+ +------------------------------------
625
+ >>>
0 commit comments