Issue #23865: close() methods in multiple modules now are idempotent and more
robust at shutdown. If needs to release multiple resources, they are released
even if errors are occured.
diff --git a/Lib/xml/sax/expatreader.py b/Lib/xml/sax/expatreader.py
index 65ac7e3..1795b23 100644
--- a/Lib/xml/sax/expatreader.py
+++ b/Lib/xml/sax/expatreader.py
@@ -211,22 +211,24 @@
             self._err_handler.fatalError(exc)
 
     def close(self):
-        if self._entity_stack:
+        if self._entity_stack or self._parser is None:
             # If we are completing an external entity, do nothing here
             return
-        self.feed("", isFinal = 1)
-        self._cont_handler.endDocument()
-        self._parsing = 0
-        # break cycle created by expat handlers pointing to our methods
-        self._parser = None
         try:
-            file = self._source.getCharacterStream()
-            if file is not None:
-                file.close()
+            self.feed("", isFinal = 1)
+            self._cont_handler.endDocument()
         finally:
-            file = self._source.getByteStream()
-            if file is not None:
-                file.close()
+            self._parsing = 0
+            # break cycle created by expat handlers pointing to our methods
+            self._parser = None
+            try:
+                file = self._source.getCharacterStream()
+                if file is not None:
+                    file.close()
+            finally:
+                file = self._source.getByteStream()
+                if file is not None:
+                    file.close()
 
     def _reset_cont_handler(self):
         self._parser.ProcessingInstructionHandler = \