"""显式记录异常原因，并验证 with 在异常路径关闭文件。"""
from pathlib import Path
from tempfile import TemporaryDirectory
import traceback


class InvalidDuration(ValueError):
    pass


def parse_duration(text):
    try:
        return int(text)
    except ValueError as exc:
        raise InvalidDuration(f"invalid duration: {text!r}") from exc


def bad_result():
    try:
        raise ValueError("lost")
    finally:
        return "looks successful"  # 覆盖正在传播的异常；不要模仿。


def main():
    try:
        try:
            raise ValueError("primary failure")
        finally:
            raise OSError("cleanup failure")
    except OSError as exc:
        assert isinstance(exc.__context__, ValueError)
        evidence = "".join(traceback.format_exception(exc))
        assert "primary failure" in evidence and "cleanup failure" in evidence
        print(evidence, end="")
    # 修复：清理错误显式收集，主错误继续传播并作为外层异常原因。
    cleanup_errors = []
    try:
        try:
            raise ValueError("primary failure")
        finally:
            try:
                raise OSError("cleanup failure")
            except OSError as cleanup:
                cleanup_errors.append(str(cleanup))
    except ValueError as primary:
        assert str(primary) == "primary failure"
        assert cleanup_errors == ["cleanup failure"]
        print("preserved primary + observed cleanup:", str(primary), cleanup_errors)
    try:
        parse_duration("slow")
    except InvalidDuration as exc:
        assert isinstance(exc.__cause__, ValueError)
        print("cause:", type(exc.__cause__).__name__)
    with TemporaryDirectory() as directory:
        path = Path(directory) / "events.txt"
        stream = None
        try:
            with path.open("w", encoding="utf-8") as stream:
                stream.write("event\n")
                raise RuntimeError("demo")
        except RuntimeError:
            assert stream is not None and stream.closed
            print("closed:", stream.closed)
    assert bad_result() == "looks successful"
    print("bad:", bad_result())


if __name__ == "__main__":
    main()
