Skip to content

Commit d025269

Browse files
committed
Fixed bare raise in a handler not raising an exception group
1 parent 4357e11 commit d025269

4 files changed

Lines changed: 31 additions & 1 deletion

File tree

CHANGES.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@ This library adheres to `Semantic Versioning 2.0 <http://semver.org/>`_.
88
- Added special monkeypatching if `Apport <https://github.com/canonical/apport>`_ has
99
overridden ``sys.excepthook`` so it will format exception groups correctly
1010
(PR by John Litborn)
11+
- Fixed bare ``raise`` in a handler reraising the original naked exception rather than
12+
an exception group which is what is raised when you do a ``raise`` in an ``except*``
13+
handler
1114

1215
**1.1.3**
1316

src/exceptiongroup/_catch.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,10 @@ def handle_exception(self, exc: BaseException) -> BaseException | None:
6464
except BaseExceptionGroup:
6565
result = handler(matched)
6666
except BaseExceptionGroup as new_exc:
67-
new_exceptions.extend(new_exc.exceptions)
67+
if new_exc is matched:
68+
new_exceptions.append(new_exc)
69+
else:
70+
new_exceptions.extend(new_exc.exceptions)
6871
except BaseException as new_exc:
6972
new_exceptions.append(new_exc)
7073
else:

tests/test_catch.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,3 +208,15 @@ def delegate(eg):
208208
with pytest.raises(TypeError, match="Exception handler must be a sync function."):
209209
with catch({TypeError: delegate}):
210210
raise ExceptionGroup("message", [TypeError("uh-oh")])
211+
212+
213+
def test_bare_reraise_from_naked_exception():
214+
def handler(eg):
215+
raise
216+
217+
with pytest.raises(ExceptionGroup) as excgrp, catch({Exception: handler}):
218+
raise KeyError("foo")
219+
220+
assert len(excgrp.value.exceptions) == 1
221+
assert isinstance(excgrp.value.exceptions[0], KeyError)
222+
assert str(excgrp.value.exceptions[0]) == "'foo'"

tests/test_catch_py311.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,3 +176,15 @@ def test_bare_raise_in_handler():
176176
assert excgrp.value is not middle_exc
177177
assert excgrp.value.__cause__ is first_exc
178178
assert excgrp.value.__context__ is first_exc
179+
180+
181+
def test_bare_reraise_from_naked_exception():
182+
with pytest.raises(ExceptionGroup) as excgrp:
183+
try:
184+
raise KeyError("foo")
185+
except* KeyError:
186+
raise
187+
188+
assert len(excgrp.value.exceptions) == 1
189+
assert isinstance(excgrp.value.exceptions[0], KeyError)
190+
assert str(excgrp.value.exceptions[0]) == "'foo'"

0 commit comments

Comments
 (0)