在不调用原始异常的情况下在 Except 中引发异常
raising an Exception in an Except without calling the original Exception
我的代码如下:
try:
*Do something*
except *anError*:
if (condition):
methodCalled()
else:
raise "my own Exception"
问题是,当我引发自己的异常 ("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'>
只有一个 active 异常;我可能写了 except TypeError
而不是 except Exception
并且输出仍然是相同的。
如果你想阻止Python打印原始异常,使用raise ... from None
:
try:
raise ValueError
except ValueError:
raise TypeError from None
我的代码如下:
try:
*Do something*
except *anError*:
if (condition):
methodCalled()
else:
raise "my own Exception"
问题是,当我引发自己的异常 ("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'>
只有一个 active 异常;我可能写了 except TypeError
而不是 except Exception
并且输出仍然是相同的。
如果你想阻止Python打印原始异常,使用raise ... from None
:
try:
raise ValueError
except ValueError:
raise TypeError from None