raising an Exception in an Except without calling the original Exception
本问题已经有最佳答案,请猛点这里访问。
我的代码如下:
1 2 3 4 5 6 7 | try: *Do something* except *anError*: if (condition): methodCalled() else: raise"my own Exception" |
问题是,当我提出自己的异常("我自己的异常")时,也会引发"anError"异常。 有没有办法确保当我提出自己的异常时,我捕获的错误不会被引发?
引用文档:
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.
这正是你的情况:
1 2 3 4 5 6 7 8 | 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'> |
只有一个活跃的例外; 我可能写了
如果要阻止Python打印原始异常,请使用
1 2 3 4 | try: raise ValueError except ValueError: raise TypeError from None |