【问题标题】:Python: chain an exception to a warningPython:将异常链接到警告
【发布时间】:2019-11-29 00:00:52
【问题描述】:

我想通过捕获异常并发出警告来处理某些异常。当显示警告时(例如,在 stderr 或日志文件中,我使用日志记录模块)我希望它显示警告的堆栈跟踪,然后显示“由”加上原始异常的堆栈跟踪。

如果我要引发另一个异常,我会使用 from 关键字(假设 XExceptionYException 是从 Exception 派生的自定义异常类,而 YWarning 是从 Warning 类派生的):

def do_x():
    riase XException("Failed to do X")

def do_y():
    try:
        # do other things
        do_x()
        # maybe do some more things
    except XException as x_exc:
        raise YException("Failed to do Y") from x_exc

但就我而言,如果做 X 失败,这没什么大不了的,我可以继续做 Y。不过我想发出警告。

from warnings import warn

def do_x():
    raise XException("Failed to do X")

def do_y():
    try:
        # do other things
        do_x() # if this fails, we can live with it
    except XException as x_exc:
        warn(YWarning("Things went not so smooth with doing Y", cause=x_exc))

这里我编写了cause= 可选参数,所以我想知道如何实例化任何Exception 子类(包括Warning 及其子类)并指定原因。

【问题讨论】:

    标签: python-3.x exception warnings


    【解决方案1】:

    所以在写这个问题时,我想出了一个可能的答案。

    ywarn = YWarning("Things went not so smooth with doing Y")
    ywarn.__cause__ = x_exc
    warn(ywarn)
    

    事实证明,根据PEP 3134from 正是这样做的。

    甚至可以实际实现虚构的cause= 可选参数。毕竟,YWarning 是一个自定义子类。

    class YWarning(Warning):
        def __init__(self, msg, cause=None):
            self.__cause__ = cause
    

    【讨论】:

      猜你喜欢
      • 2011-08-04
      • 2012-04-24
      • 2018-05-22
      • 2013-05-01
      • 2014-01-17
      • 2023-03-17
      • 1970-01-01
      • 2020-01-18
      • 2012-09-22
      相关资源
      最近更新 更多