Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 303de6a

Browse files
committed
Fix (and add test for) missing check for BaseException subclasses in the C
API.
1 parent 4f564bd commit 303de6a

2 files changed

Lines changed: 28 additions & 1 deletion

File tree

Lib/test/test_exceptions.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -171,10 +171,15 @@ def ckmsg(src, msg):
171171
# test that setting an exception at the C level works even if the
172172
# exception object can't be constructed.
173173

174-
class BadException:
174+
class BadException(Exception):
175175
def __init__(self):
176176
raise RuntimeError, "can't instantiate BadException"
177177

178+
# Exceptions must inherit from BaseException, raising invalid exception
179+
# should instead raise SystemError
180+
class InvalidException:
181+
pass
182+
178183
def test_capi1():
179184
import _testcapi
180185
try:
@@ -201,8 +206,21 @@ def test_capi2():
201206
else:
202207
print "Expected exception"
203208

209+
def test_capi3():
210+
import _testcapi
211+
try:
212+
_testcapi.raise_exception(InvalidException, 1)
213+
except SystemError:
214+
pass
215+
except InvalidException:
216+
raise AssertionError("Managed to raise InvalidException");
217+
else:
218+
print "Expected SystemError exception"
219+
220+
204221
if not sys.platform.startswith('java'):
205222
test_capi1()
206223
test_capi2()
224+
test_capi3()
207225

208226
unlink(TESTFN)

Python/errors.c

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,15 @@ PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
4747
void
4848
PyErr_SetObject(PyObject *exception, PyObject *value)
4949
{
50+
if (exception != NULL &&
51+
!PyExceptionClass_Check(exception)) {
52+
PyObject *excstr = PyObject_Repr(exception);
53+
PyErr_Format(PyExc_SystemError,
54+
"exception %s not a BaseException subclass",
55+
PyString_AS_STRING(excstr));
56+
Py_DECREF(excstr);
57+
return;
58+
}
5059
Py_XINCREF(exception);
5160
Py_XINCREF(value);
5261
PyErr_Restore(exception, value, (PyObject *)NULL);

0 commit comments

Comments
 (0)