python - python 中的错误处理程序

标签 python error-handling refactoring try-except contextmanager

我很难找到执行此操作的“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/

相关文章:

python - 苹果操作系统 : unable to use virtualenv

Python Pandas.Series.asof : Cannot compare type 'Timestamp' with type 'struct_time'

python - 值的长度与索引的长度不匹配

java - 有两个结构相同但细节不同的函数。如何摆脱重复?

python - 在列表/字典错误中搜索

Scala:是否是唯一的选择?

IOS:当网络不可用时使用 stringWithContentsOfURL

php - 需要帮助重构我的冗余代码(使用 MySQL/PHP 来填充/构建 3 个选择列表)

reference - 如何在 csproj 中找到不需要的 PackageReference

error-handling - UDP协议(protocol)是否有一些错误检测?