Skip to content

Commit

Permalink
Fixed bare raise in a handler not raising an exception group
Browse files Browse the repository at this point in the history
  • Loading branch information
agronholm committed Nov 21, 2023
1 parent 4357e11 commit d025269
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 1 deletion.
3 changes: 3 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ This library adheres to `Semantic Versioning 2.0 <http://semver.org/>`_.
- Added special monkeypatching if `Apport <https://github.com/canonical/apport>`_ has
overridden ``sys.excepthook`` so it will format exception groups correctly
(PR by John Litborn)
- Fixed bare ``raise`` in a handler reraising the original naked exception rather than
an exception group which is what is raised when you do a ``raise`` in an ``except*``
handler

**1.1.3**

Expand Down
5 changes: 4 additions & 1 deletion src/exceptiongroup/_catch.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,10 @@ def handle_exception(self, exc: BaseException) -> BaseException | None:
except BaseExceptionGroup:
result = handler(matched)
except BaseExceptionGroup as new_exc:
new_exceptions.extend(new_exc.exceptions)
if new_exc is matched:
new_exceptions.append(new_exc)
else:
new_exceptions.extend(new_exc.exceptions)
except BaseException as new_exc:
new_exceptions.append(new_exc)
else:
Expand Down
12 changes: 12 additions & 0 deletions tests/test_catch.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,3 +208,15 @@ def delegate(eg):
with pytest.raises(TypeError, match="Exception handler must be a sync function."):
with catch({TypeError: delegate}):
raise ExceptionGroup("message", [TypeError("uh-oh")])


def test_bare_reraise_from_naked_exception():
def handler(eg):
raise

with pytest.raises(ExceptionGroup) as excgrp, catch({Exception: handler}):
raise KeyError("foo")

assert len(excgrp.value.exceptions) == 1
assert isinstance(excgrp.value.exceptions[0], KeyError)
assert str(excgrp.value.exceptions[0]) == "'foo'"
12 changes: 12 additions & 0 deletions tests/test_catch_py311.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,3 +176,15 @@ def test_bare_raise_in_handler():
assert excgrp.value is not middle_exc
assert excgrp.value.__cause__ is first_exc
assert excgrp.value.__context__ is first_exc


def test_bare_reraise_from_naked_exception():
with pytest.raises(ExceptionGroup) as excgrp:
try:
raise KeyError("foo")
except* KeyError:
raise

assert len(excgrp.value.exceptions) == 1
assert isinstance(excgrp.value.exceptions[0], KeyError)
assert str(excgrp.value.exceptions[0]) == "'foo'"

0 comments on commit d025269

Please sign in to comment.