[2.7] bpo-34068: iobase_close could call PyObject_SetAttrString with an exception set (GH-8282). (GH-8312) (GH-8314)

(cherry picked from commit 28f07364f066792ceee93231dbb80ae8ad98b2bb)

Co-authored-by: Zackery Spytz <zspytz@gmail.com>.
(cherry picked from commit cc13016658a9ed86d0b702ab6c251ad5952a952f)
diff --git a/Modules/_io/iobase.c b/Modules/_io/iobase.c
index d813daf..17b905a 100644
--- a/Modules/_io/iobase.c
+++ b/Modules/_io/iobase.c
@@ -177,17 +177,25 @@
 static PyObject *
 iobase_close(PyObject *self, PyObject *args)
 {
-    PyObject *res;
+    PyObject *res, *exc, *val, *tb;
+    int rc;
 
     if (IS_CLOSED(self))
         Py_RETURN_NONE;
 
     res = PyObject_CallMethodObjArgs(self, _PyIO_str_flush, NULL);
-    PyObject_SetAttrString(self, "__IOBase_closed", Py_True);
+
+    PyErr_Fetch(&exc, &val, &tb);
+    rc = PyObject_SetAttrString(self, "__IOBase_closed", Py_True);
+    _PyErr_ReplaceException(exc, val, tb);
+    if (rc < 0) {
+        Py_CLEAR(res);
+    }
+
     if (res == NULL) {
         return NULL;
     }
-    Py_XDECREF(res);
+    Py_DECREF(res);
     Py_RETURN_NONE;
 }