示例工程 09-exceptions-context-managers

09-exceptions-context-managers/01-finally-vs-return/finally_vs_return.py

python · 0.9 KB

"""演示 finally 中的 return 如何吞掉异常/覆盖返回值。"""
 
from __future__ import annotations
 
 
def swallow_exception() -> str:
    """finally 的 return 会丢弃正在传播的异常。"""
    try:
        raise ValueError("boom")
    finally:
        return "from-finally"
 
 
def override_return() -> str:
    """finally 的 return 覆盖 try 的返回值。"""
    try:
        return "try"
    finally:
        return "finally"
 
 
def run_order() -> list[str]:
    events: list[str] = []
    try:
        events.append("try")
        raise RuntimeError("x")
    except RuntimeError:
        events.append("except")
        raise
    finally:
        events.append("finally")
 
 
def main() -> None:
    print(f"swallow: {swallow_exception()}")
    print(f"override: {override_return()}")
    try:
        run_order()
    except RuntimeError as exc:
        print(f"propagated: {exc}")
 
 
if __name__ == "__main__":
    main()