最后并在异常中排除异常,在python中引发 [英] finally and rethowing of exception in except, raise in python

查看:112
本文介绍了最后并在异常中排除异常,在python中引发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

Why the output is in the following formats?

输出:

error
finally
malicious error

实际上我期望是:

error
malicious error
finally

为什么呢?

推荐答案

miexp("malicious error")未处理,因此将结束程序的执行.另一方面,保证要执行.

miexp("malicious error") isn't handled, therefore it will end the execution of the program. On the other hand, the finally block is guaranteed to be executed.

为确保此Python在实际引发异常之前在 之前执行finally块.从文档:

To ensure this Python executes the finally block before actually raising the exception. From the documentation:

如果任何子句中发生异常并且未对其进行处理,则该异常将被临时保存.将执行finally子句.如果有保存的异常,它将在finally子句的末尾重新引发.

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.

这篇关于最后并在异常中排除异常,在python中引发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆