最后,在except中重新显示异常,在python中引发

2024-05-16 22:30:52 发布

您现在位置:Python中文网/ 问答频道 /正文

try:
   #error code
except Exception as e:
   print 'error',e
   raise miexp("malicious error")  
   #userdefined exception, miexp
finally:
   print 'finally'

为什么输出采用以下格式?

输出:

error
finally
malicious error

实际上我希望是:

error
malicious error
finally

为什么?


Tags: as格式exceptioncodeerrorraisemaliciousprint
1条回答
网友
1楼 · 发布于 2024-05-16 22:30:52

miexp("malicious error")未被处理,因此它将结束程序的执行。另一方面,保证执行finally块。

为了确保这个Python在实际引发异常之前执行finally。从documentation

If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception it is re-raised at the end of the finally clause.

相关问题 更多 >