在 Python 的异常处理程序中引发异常的惯用方法是什么?

问题描述

Python 中捕获异常并引发另一个异常的正确方法是什么?即,我想捕获类型 1 的异常,操作 Exception 对象并无条件地引发类型 2 的第二个异常,以便调用函数看不到类型 1 的异常,但绝对可以看到其构造的类型 2 的异常取决于从类型 1 异常访问的数据。

这是我试过但不起作用的代码

            def d(wrt):
                try:
                    return rt.derivative(wrt).canonicalize()
                except CannotComputeDerivative as e:
                    msg = "\n".join([f"When generating derivatives from {self}",f"  when computing edges of {rt}",f"  which canonicalizes to {self.canonicalize()}",f"  computing derivative of {e.rte}",f"  wrt={e.wrt}",f"  derivatives() reported: {e.msg}"])
                    raise CannotComputeDerivatives(msg=msg,rte=rt,wrt=wrt,first_types=fts,mdtd=wrts)

我认为它不起作用的原因是因为我收到以下消息作为输出

Error
Traceback (most recent call last):
  File "/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py",line 95,in d
    return rt.derivative(wrt).canonicalize()
  File "/Users/jnewton/Repos/python-rte/pyrte/rte/r_singleton.py",line 68,in derivative
    return super().derivative(wrt)
  File "/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py",line 72,in derivative
    return self.derivative_down(wrt)
  File "/Users/jnewton/Repos/python-rte/pyrte/rte/r_singleton.py",line 91,in derivative_down
    raise CannotComputeDerivative(
rte.r_rte.CannotComputeDerivative

During handling of the above exception,another exception occurred:

Traceback (most recent call last):
  File "/Users/jnewton/Repos/python-rte/pyrte/tests/rte_tests.py",line 615,in test_derivatives
    self.assertTrue(rt.derivatives())
  File "/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py",line 111,in derivatives
    return trace_graph(self,edges)
  File "/Users/jnewton/Repos/python-rte/pyrte/genus/utils.py",line 199,in trace_graph
    es = edges(v0)  # List[(L,V)]
  File "/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py",line 109,in edges
    return [(td,d(td)) for td in wrts]
  File "/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py",in <listcomp>
    return [(td,line 103,in d
    raise CannotComputeDerivatives(msg=msg,rte.r_rte.CannotComputeDerivatives

按照 MisterMiyagi 的建议,我在 from None 之后添加raise CannotComputeDerivatives(...)。这取得了进展,但似乎 unittest 环境并不真正喜欢它。单元测试期间显示的消息如下所示。看起来 unittest 遗憾地截断了消息。

Error
Traceback (most recent call last):
  File "/Users/jnewton/Repos/python-rte/pyrte/tests/rte_tests.py",in test_derivatives
    rt.derivatives()
  File "/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py",rte.r_rte.CannotComputeDerivatives

============ 要跟进解决方案: 最初的问题是 __init__ 类的 CannotComputeDerivatives 函数调用 super().__init__() 时没有传递消息字符串。我更新了类定义如下。

class CannotComputeDerivatives(Exception):
    def __init__(self,msg,rte,wrt,first_types,mdtd):
        self.msg = msg
        self.rte = rte
        self.wrt = wrt
        self.first_types = first_types
        self.mdtd = mdtd
        super().__init__(msg)

结果是我在单元测试期间收到漂亮的错误消息:

Error
Traceback (most recent call last):
  File "/Users/jnewton/Repos/python-rte/pyrte/tests/rte_tests.py",rte.r_rte.CannotComputeDerivatives: When generating derivatives from Singleton(SOr(odd?,SAtomic(Test2)))
  when computing edges of Singleton(SOr(odd?,SAtomic(Test2)))
  which canonicalizes to Singleton(SOr(odd?,SAtomic(Test2)))
  computing derivative of Singleton(SOr(odd?,SAtomic(Test2)))
  wrt=SOr(SAtomic(Test2),odd?)
  derivatives() reported: Singleton.derivative_down cannot compute derivative of Singleton(SOr(odd?,odd?)
  disjoint=False
  subtypep=None

解决方法

感谢@MisterMiyagi 建议在 from None 后添加 raise ...。这样就避免了系统在异常中报异常的问题。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...