我的代码如下:
try:
*Do something*
except *anError*:
if (condition):
methodCalled()
else:
raise "my own Exception"
问题是,当我引发自己的异常(“我自己的异常”)时,也会引发“anError”异常。有没有办法确保当我引发自己的异常时,我捕获的错误不会引发?
最佳答案
引用docs :
When raising (or re-raising) an exception in an except or finally clause __context__ is automatically set to the last exception caught; if the new exception is not handled the traceback that is eventually displayed will include the originating exception(s) and the final exception.
这正是您的情况:
try:
try:
raise ValueError
except ValueError:
raise TypeError
except Exception as e:
print('Original:', type(e.__context__)) # Original: <class 'ValueError'>
print('Explicitly raised:', type(e)) # Explicitly raised: <class 'TypeError'>
只有一个事件异常;我可能写了 except TypeError
而不是 except Exception
,并且输出仍然是相同的。
如果要阻止 Python 打印原始异常,请使用 raise ... from None
:
try:
raise ValueError
except ValueError:
raise TypeError from None
关于python - 在 except 中引发异常而不调用原始异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28028173/