2019-02-27
阅读量:
606
python如何定义清理操作
想想你总是希望程序做的任务,无论是完美运行还是引发任何类型的错误。例如,我们使用try语句,它有一个可选子句 -“finally”来执行清理操作,必须在所有条件下执行。
清理操作:在离开try语句之前,始终执行“finally”子句,无论是否引发任何异常。这些条款旨在定义必须在所有情况下执行的清理行动。
每当发生异常并且没有由except子句处理时,首先最终会发生,然后将错误引发为默认[代码3]。
# Python code to illustrate
# clean up actions
def divide(x, y):
try:
# Floor Division : Gives only Fractional Part as Answer
result = x // y
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
else:
print("Yeah ! Your answer is :", result)
finally:
print("I'm finally clause, always raised !! ")
# Look at parameters and note the working of Program
divide(3, 2)
输出 :
Yeah ! Your answer is : 1
I'm finally clause, always raised !!






评论(0)


暂无数据
推荐帖子
0条评论
0条评论
1条评论