python try:except:finally [英] python try:except:finally
问题描述
# Open new file to write
file = None
try:
file = open(filePath, 'w')
except IOError:
msg = ("Unable to create file on disk.")
file.close()
return
finally:
file.write("Hello World!")
file.close()
以上代码是从函数中剥离的。用户的系统之一正在报告错误:
The above code is ripped from a function. One of the user's system is reporting an error in line:
file.write("Hello World!")
错误:
AttributeError: 'NoneType' object has no attribute 'write'
问题是,如果python失败,打开给定文件,执行 except块,它必须返回
,但控制权已转移到引发给定错误的行。
Question is, If python is failed to open given file, 'except' block executes and it has to return, but control is getting transferred to the line that is throwing given error. The value of 'file' variable is 'None'.
是否有指针?
推荐答案
您不应该在 finally
块中写入文件,因为在那里引发的任何异常都不会被捕获,
块。
You shouldn't be writing to the file in the finally
block as any exceptions raised there will not be caught by the except
block.
如果try块引发异常,则执行 except
块。 最终
块总是执行任何发生的事情。
The except
block executes if there is an exception raised by the try block. The finally
block always executes whatever happens.
此外,不应将文件
变量初始化为 none
的任何需要。
Also, there shouldn't be any need for initializing the file
variable to none
.
在除外
块中使用返回
不会最终跳过
块。从本质上讲,它不能被跳过,这就是为什么要在其中放置清理代码(即关闭文件)。
The use of return
in the except
block will not skip the finally
block. By its very nature it cannot be skipped, that's why you want to put your "clean-up" code in there (i.e. closing files).
因此,如果您要要使用try:except:finally,您应该这样做:
So, if you want to use try:except:finally, you should be doing something like this:
try:
f = open("file", "w")
try:
f.write('Hello World!')
finally:
f.close()
except IOError:
print 'oops!'
一种更清洁的方法是使用 with
语句:
A much cleaner way of doing this is using the with
statement:
try:
with open("output", "w") as outfile:
outfile.write('Hello World')
except IOError:
print 'oops!'
这篇关于python try:except:finally的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!