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

Skip to content

Commit 5d6fbe8

Browse files
committed
Instantiate the OS-related exception as soon as we raise it, so that
"except" works properly.
1 parent 1e4fe70 commit 5d6fbe8

2 files changed

Lines changed: 22 additions & 6 deletions

File tree

Lib/test/test_pep3151.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,18 @@ def test_OSError_subclass_mapping(self):
7979
e = SubOSError(EEXIST, "Bad file descriptor")
8080
self.assertIs(type(e), SubOSError)
8181

82+
def test_try_except(self):
83+
# This checks that try .. except checks the concrete exception
84+
# (FileNotFoundError) and not the base type specified when
85+
# PyErr_SetFromErrnoWithFilenameObject was called.
86+
# (it is therefore deliberate that it doesn't use assertRaises)
87+
try:
88+
open("some_hopefully_non_existing_file")
89+
except FileNotFoundError:
90+
pass
91+
else:
92+
self.fail("should have raised a FileNotFoundError")
93+
8294

8395
class AttributesTest(unittest.TestCase):
8496

Python/errors.c

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -341,7 +341,7 @@ PyObject *
341341
PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
342342
{
343343
PyObject *message;
344-
PyObject *v;
344+
PyObject *v, *args;
345345
int i = errno;
346346
#ifndef MS_WINDOWS
347347
char *s;
@@ -410,14 +410,18 @@ PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
410410
}
411411

412412
if (filenameObject != NULL)
413-
v = Py_BuildValue("(iOO)", i, message, filenameObject);
413+
args = Py_BuildValue("(iOO)", i, message, filenameObject);
414414
else
415-
v = Py_BuildValue("(iO)", i, message);
415+
args = Py_BuildValue("(iO)", i, message);
416416
Py_DECREF(message);
417417

418-
if (v != NULL) {
419-
PyErr_SetObject(exc, v);
420-
Py_DECREF(v);
418+
if (args != NULL) {
419+
v = PyObject_Call(exc, args, NULL);
420+
Py_DECREF(args);
421+
if (v != NULL) {
422+
PyErr_SetObject((PyObject *) Py_TYPE(v), v);
423+
Py_DECREF(v);
424+
}
421425
}
422426
#ifdef MS_WINDOWS
423427
LocalFree(s_buf);

0 commit comments

Comments
 (0)