【发布时间】:2013-06-04 18:52:00
【问题描述】:
我应该如何“重新抛出”异常,即假设:
- 我在我的代码中尝试了一些东西,但不幸的是它失败了。
- 我尝试了一些“聪明”的解决方法,但这次也失败了
如果我从(失败的)解决方法中抛出异常,用户会非常困惑,所以我认为最好重新抛出原始异常 (?),带有描述性回溯(关于实际问题)...
注意:这方面的激励示例是在调用np.log(np.array(['1'], dtype=object)) 时,它是tries a witty workaround and gives an AttributeError(它“真的”是TypeError)。
我能想到的一种方法就是重新调用有问题的函数,但这似乎是顽固的(一方面,理论上原始函数在第二次调用时可能会表现出一些不同的行为):
好的这是一个糟糕的例子,但是这里......
def f():
raise Exception("sparrow")
def g():
raise Exception("coconut")
def a():
f()
假设我这样做了:
try:
a()
except:
# attempt witty workaround
g()
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-4-c76b7509b315> in <module>()
3 except:
4 # attempt witty workaround
----> 5 g()
6
<ipython-input-2-e641f2f9a7dc> in g()
4
5 def g():
----> 6 raise Exception("coconut")
7
8
Exception: coconut
嗯,问题根本不在于椰子,而在于麻雀:
try:
a()
except:
# attempt witty workaround
try:
g()
except:
# workaround failed, I want to rethrow the exception from calling a()
a() # ideally don't want to call a() again
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-4-e641f2f9a7dc> in <module>()
19 except:
20 # workaround failed, I want to rethrow the exception from calling a()
---> 21 a() # ideally don't want to call a() again
<ipython-input-3-e641f2f9a7dc> in a()
8
9 def a():
---> 10 f()
11
12
<ipython-input-1-e641f2f9a7dc> in f()
1 def f():
----> 2 raise Exception("sparrow")
3
4
5 def g():
Exception: sparrow
有没有标准的方法来处理这个问题,还是我认为它完全错误?
【问题讨论】:
-
你试过traceback模块吗?
-
@kirbyfan64sos 是否愿意使用它来汇总答案?
-
您认为应该重新引发原始异常的直觉是正确的:这就是在 Java try-with-resources 中所做的(相当于 Python
with语句),但 Java 还添加了次要异常作为通过Throwable#addSuppressed的“抑制”异常,因此您实际上可以获得tree 异常!见Who decides what exceptions get suppressed?。
标签: python exception exception-handling