我正在尝试创建通用异常处理程序 - 我可以设置一个 arg 以在异常情况下返回,灵感来自这个答案。
import contextlib
@contextlib.contextmanager
def handler(default):
try:
yield
except Exception as e:
yield default
def main():
with handler(0):
return 1 / 0
with handler(0):
return 100 / 0
with handler(0):
return 'helllo + 'cheese'
但这导致
RuntimeError: generator didn't stop after throw()