Skip to content

Commit 8f71b34

Browse files
authored
gh-112217: Add check to call result for do_raise() where cause is a type. (#112216)
1 parent 4dcfd02 commit 8f71b34

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

Lib/test/test_raise.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,20 @@ def test_class_cause(self):
185185
else:
186186
self.fail("No exception raised")
187187

188+
def test_class_cause_nonexception_result(self):
189+
class ConstructsNone(BaseException):
190+
@classmethod
191+
def __new__(*args, **kwargs):
192+
return None
193+
try:
194+
raise IndexError from ConstructsNone
195+
except TypeError as e:
196+
self.assertIn("should have returned an instance of BaseException", str(e))
197+
except IndexError:
198+
self.fail("Wrong kind of exception raised")
199+
else:
200+
self.fail("No exception raised")
201+
188202
def test_instance_cause(self):
189203
cause = KeyError()
190204
try:
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add check for the type of ``__cause__`` returned from calling the type ``T`` in ``raise from T``.

Python/ceval.c

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1920,6 +1920,13 @@ do_raise(PyThreadState *tstate, PyObject *exc, PyObject *cause)
19201920
fixed_cause = _PyObject_CallNoArgs(cause);
19211921
if (fixed_cause == NULL)
19221922
goto raise_error;
1923+
if (!PyExceptionInstance_Check(fixed_cause)) {
1924+
_PyErr_Format(tstate, PyExc_TypeError,
1925+
"calling %R should have returned an instance of "
1926+
"BaseException, not %R",
1927+
cause, Py_TYPE(fixed_cause));
1928+
goto raise_error;
1929+
}
19231930
Py_DECREF(cause);
19241931
}
19251932
else if (PyExceptionInstance_Check(cause)) {

0 commit comments

Comments
 (0)