python中tryfinally的⽤法_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"
python的try和except用法fh.close()
except IOError:
print "Error: can\'t find file or read data"
当try块中引发异常时,执⾏⽴即转到finally块。执⾏完finally块中的所有语句后,如果在try-except语句的下⼀个较⾼层中存在,则再次引发异常,并在except语句中对其进⾏处理。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论