diff --git a/doc/source/whatsnew/v1.4.3.rst b/doc/source/whatsnew/v1.4.3.rst index b78188409d350..54cad82366e43 100644 --- a/doc/source/whatsnew/v1.4.3.rst +++ b/doc/source/whatsnew/v1.4.3.rst @@ -30,7 +30,7 @@ Fixed regressions Bug fixes ~~~~~~~~~ -- +- Most I/O methods do no longer suppress ``OSError`` and ``ValueError`` when closing file handles (:issue:`47136`) - .. --------------------------------------------------------------------------- diff --git a/pandas/io/common.py b/pandas/io/common.py index 0331d320725ac..f02c43da7cdb1 100644 --- a/pandas/io/common.py +++ b/pandas/io/common.py @@ -112,11 +112,8 @@ def close(self) -> None: self.handle.flush() self.handle.detach() self.created_handles.remove(self.handle) - try: - for handle in self.created_handles: - handle.close() - except (OSError, ValueError): - pass + for handle in self.created_handles: + handle.close() self.created_handles = [] self.is_wrapped = False diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py index 36048601b3248..25a36c86eeaae 100644 --- a/pandas/tests/io/test_common.py +++ b/pandas/tests/io/test_common.py @@ -600,3 +600,15 @@ def test_fail_mmap(): with pytest.raises(UnsupportedOperation, match="fileno"): with BytesIO() as buffer: icom.get_handle(buffer, "rb", memory_map=True) + + +def test_close_on_error(): + # GH 47136 + class TestError: + def close(self): + raise OSError("test") + + with pytest.raises(OSError, match="test"): + with BytesIO() as buffer: + with icom.get_handle(buffer, "rb") as handles: + handles.created_handles.append(TestError())