python中try finally的用法_Python中的try-finally子句

您可以将finally:块与try:块一起使用。finally块是放置必须执行的所有代码的位置,无论try块是否引发异常。try-finally语句的语法是:try:

You do your operations here;

......................

Due to any exception, this may be skipped.

finally:

This would always be executed.

......................

您不能同时使用else子句和finally子句。

示例#!/usr/bin/python

try:

fh = open("testfile", "w")

fh.write("This is my test file for exception handling!!")

finally:

print "Error: can\'t find file or read data"

输出结果

如果您无权以写入模式打开文件,则将产生以下结果-Error: can't find file or read data

相同的例子可以更清晰地写成如下-

示例#!/usr/bin/python

try:

fh = open("testfile", "w")

try:

fh.write("This is my test file for exception handling!!")

finally:

print "Going to close the file"

fh.close()

except IOError:

print "Error: can\'t find file or read data"

当try块中引发异常时,执行立即转到finally块。执行完finally块中的所有语句后,如果在try-except语句的下一个较高层中存在,则再次引发异常,并在except语句中对其进行处理。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值