Kedua tipe pengecualian ini membungkus pengecualian dalam urutan excs. Parameter pesan harus berupa string. Perbedaan antara kedua kelas tersebut adalah BaseExceptionGroup memperluas BaseException dan dapat membungkus pengecualian apa pun, sedangkan ExceptionGroup memperluas Exception dan hanya dapat membungkus subkelas dari Exception. Desain ini dimaksudkan agar Exception menangkap ExceptionGroup tetapi tidak menangkap BaseExceptionGroup.
exception BaseExceptionGroup(msg, excs)
>>> class MyGroup(ExceptionGroup):
... def derive(self, excs):
... return MyGroup(self.message, excs)
...
>>> e = MyGroup("eg", [ValueError(1), TypeError(2)])
>>> e.add_note("a note")
>>> e.__context__ = Exception("context")
>>> e.__cause__ = Exception("cause")
>>> try:
... raise e
... except Exception as e:
... exc = e
...
>>> match, rest = exc.split(ValueError)
>>> exc, exc.__context__, exc.__cause__, exc.__notes__
(MyGroup('eg', [ValueError(1), TypeError(2)]), Exception('context'), Exception('cause'), ['a note'])
>>> match, match.__context__, match.__cause__, match.__notes__
(MyGroup('eg', [ValueError(1)]), Exception('context'), Exception('cause'), ['a note'])
>>> rest, rest.__context__, rest.__cause__, rest.__notes__
(MyGroup('eg', [TypeError(2)]), Exception('context'), Exception('cause'), ['a note'])
>>> exc.__traceback__ is match.__traceback__ is rest.__traceback__
True
class Errors(ExceptionGroup):
def __new__(cls, errors, exit_code):
self = super().__new__(Errors, f"exit code: {exit_code}", errors)
self.exit_code = exit_code
return self
def derive(self, excs):
return Errors(excs, self.exit_code)