我很难找到执行此操作的“pythonic”方法: 我需要使用相同的 try-except 模式捕获不同的代码块。 要捕获的 block 彼此不同。 目前,我在代码的几个点重复相同的 try-except 模式,并包含一长串异常。
try:
block to catch
except E1, e:
log and do something
except E2, e:
log and do something
...
except Exception, e:
log and do something
使用with 语句 和上下文管理器 装饰器可以解决这个问题:
from contextlib import contextmanager
@contextmanager
def error_handler():
try:
yield
except E1, e:
log and do something
...
except Exception, e:
log and do something
...
with error_handler():
block to catch
...
但是,如果我需要知道 block 中是否有异常,会发生什么情况?即,对于 try-except-else,有没有其他方法可以像之前的 with block 那样做一些事情?
用例示例:
for var in vars:
try:
block to catch
except E1, e:
log and do something
# continue to the next loop iteration
except E2, e:
log and do something
# continue to the next loop iteration
...
except Exception, e:
log and do something
# continue to the next loop iteration
else:
do something else
我可以用 Pythonic 的方式做类似的事情来避免一次又一次地重复相同的 try-except 模式吗?
最佳答案
我可以看到您已经得到了答案,但是在您已有的基础上,您可以返回一个指示错误状态的对象,并使用它来检查您的循环。
虽然在使用这种风格之前,你应该真正考虑在这种结构中隐藏错误处理/日志记录是否真的是你想要做的事情,“Pythonic”通常更倾向于明确而不是隐藏细节。
from contextlib import contextmanager
@contextmanager
def error_handler():
error = True
try:
class Internal:
def caughtError(self): return error
yield Internal()
except Exception as e:
print("Logging#1")
except BaseException as e:
print("Logging#2")
else:
error = False
with error_handler() as e:
print("here")
# raise Exception("hopp")
print(e.caughtError()) # True if an error was logged, False otherwise
关于python - python 中的错误处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23405118/