]> granicus.if.org Git - python/commitdiff
Instantiate the OS-related exception as soon as we raise it, so that "except"
authorVictor Stinner <victor.stinner@haypocalc.com>
Mon, 17 Oct 2011 18:18:58 +0000 (20:18 +0200)
committerVictor Stinner <victor.stinner@haypocalc.com>
Mon, 17 Oct 2011 18:18:58 +0000 (20:18 +0200)
works properly.

PyErr_SetFromErrnoWithFilenameObject() was already fixed by the changeset
793c75177d28. This commit fixes PyErr_SetExcFromWindowsErrWithFilenameObject(),
used on Windows.

Lib/test/test_pep3151.py
Python/errors.c

index 3c52bc6a1aa9454099bf9c26704935726014bfd7..e327f42301498e2a3865a7cbd02cafe46f895286 100644 (file)
@@ -80,12 +80,23 @@ class HierarchyTest(unittest.TestCase):
         self.assertIs(type(e), SubOSError)
 
     def test_try_except(self):
+        filename = "some_hopefully_non_existing_file"
+
         # This checks that try .. except checks the concrete exception
         # (FileNotFoundError) and not the base type specified when
         # PyErr_SetFromErrnoWithFilenameObject was called.
         # (it is therefore deliberate that it doesn't use assertRaises)
         try:
-            open("some_hopefully_non_existing_file")
+            open(filename)
+        except FileNotFoundError:
+            pass
+        else:
+            self.fail("should have raised a FileNotFoundError")
+
+        # Another test for PyErr_SetExcFromWindowsErrWithFilenameObject()
+        self.assertFalse(os.path.exists(filename))
+        try:
+            os.unlink(filename)
         except FileNotFoundError:
             pass
         else:
index d62648ba3abeb05f437ae3d6fbbcd49fe1839dd3..cd0f68dff459cebddadbe61e7608b52cd338e0a6 100644 (file)
@@ -468,7 +468,7 @@ PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
     int len;
     WCHAR *s_buf = NULL; /* Free via LocalFree */
     PyObject *message;
-    PyObject *v;
+    PyObject *args, *v;
     DWORD err = (DWORD)ierr;
     if (err==0) err = GetLastError();
     len = FormatMessageW(
@@ -504,12 +504,16 @@ PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
         filenameObject = Py_None;
     /* This is the constructor signature for passing a Windows error code.
        The POSIX translation will be figured out by the constructor. */
-    v = Py_BuildValue("(iOOi)", 0, message, filenameObject, err);
+    args = Py_BuildValue("(iOOi)", 0, message, filenameObject, err);
     Py_DECREF(message);
 
-    if (v != NULL) {
-        PyErr_SetObject(exc, v);
-        Py_DECREF(v);
+    if (args != NULL) {
+        v = PyObject_Call(exc, args, NULL);
+        Py_DECREF(args);
+        if (v != NULL) {
+            PyErr_SetObject((PyObject *) Py_TYPE(v), v);
+            Py_DECREF(v);
+        }
     }
     LocalFree(s_buf);
     return NULL;