gh-112217: Add check to call result for do_raise() where cause is a type. (#112216)

This commit is contained in:
apaz 2023-11-27 15:13:27 -06:00 committed by GitHub
parent 4dcfd02bed
commit 8f71b349de
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 22 additions and 0 deletions

View file

@ -185,6 +185,20 @@ def test_class_cause(self):
else:
self.fail("No exception raised")
def test_class_cause_nonexception_result(self):
class ConstructsNone(BaseException):
@classmethod
def __new__(*args, **kwargs):
return None
try:
raise IndexError from ConstructsNone
except TypeError as e:
self.assertIn("should have returned an instance of BaseException", str(e))
except IndexError:
self.fail("Wrong kind of exception raised")
else:
self.fail("No exception raised")
def test_instance_cause(self):
cause = KeyError()
try:

View file

@ -0,0 +1 @@
Add check for the type of ``__cause__`` returned from calling the type ``T`` in ``raise from T``.

View file

@ -1920,6 +1920,13 @@ do_raise(PyThreadState *tstate, PyObject *exc, PyObject *cause)
fixed_cause = _PyObject_CallNoArgs(cause);
if (fixed_cause == NULL)
goto raise_error;
if (!PyExceptionInstance_Check(fixed_cause)) {
_PyErr_Format(tstate, PyExc_TypeError,
"calling %R should have returned an instance of "
"BaseException, not %R",
cause, Py_TYPE(fixed_cause));
goto raise_error;
}
Py_DECREF(cause);
}
else if (PyExceptionInstance_Check(cause)) {