异常-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()
上面的代码是从函数中提取的。 用户的系统之一正在报告以下错误:
file.write("Hello World!")
错误:
AttributeError: 'NoneType' object has no attribute 'write'
问题是,如果python无法打开给定文件,则执行“ except”块,并且必须返回,但控制权转移到抛出给定错误的行。 “文件”变量的值为“无”。
有指针吗?
8个解决方案
97 votes
您不应在with块中写入文件,因为那里引发的任何异常都不会被except块捕获。
如果try块引发异常,则执行with块。 except块始终执行所有发生的事情。
另外,不需要将with变量初始化为except。
在except块中使用with不会跳过finally块。 从本质上讲,它不能被跳过,这就是为什么要在其中放置“清理”代码(即关闭文件)的原因。
因此,如果您想使用try:except:final,则应该执行以下操作:
try:
f = open("file", "w")
try:
f.write('Hello World!')
finally:
f.close()
except IOError:
print 'oops!'
一种更干净的方法是使用with语句:
try:
with open("output", "w") as outfile:
outfile.write('Hello World')
except IOError:
print 'oops!'
Acorn answered 2020-07-11T12:38:45Z
28 votes
如果未打开文件,则行IOError失败,因此不会将任何内容分配给write。
然后,IOError子句运行,但是文件中没有任何内容,因此write失败。
IOError子句始终运行,即使有异常也是如此。 而且由于write仍然为None,您将得到另一个异常。
您希望使用IOError子句而不是write子句来处理仅在没有例外的情况下才会发生的事情。
try:
file = open(filePath, 'w')
except IOError:
msg = "Unable to create file on disk."
return
else:
file.write("Hello World!")
file.close()
为什么是IOError? Python文档说:
使用else子句比向try子句添加其他代码更好,因为它避免了意外捕获try ... except语句保护的代码未引发的异常。
换句话说,这不会捕获来自write或close调用的IOError。 这样做很好,因为这样就不会出现“无法在磁盘上创建文件”的原因。 –可能是另一种错误,您的代码没有准备好。 最好不要尝试处理此类错误。
Petr Viktorin answered 2020-07-11T12:39:32Z
4 votes
包括在内的逻辑是什么
finally
在finally子句中? 我认为必须将其放在try子句中。
try:
file = open(filePath, 'w')
file.write("Hello World!")
except IOError:
print("Unable to create file on disk.")
finally:
file.close()
Sreenath Nannat answered 2020-07-11T12:39:56Z
1 votes
除了不执行(因为类型是IOError),它是最后一部分,引发另一个AttributeError类型的错误,因为file = None。
TigOldBitties answered 2020-07-11T12:40:16Z
1 votes
您可以执行以下操作:
try:
do_some_stuff()
finally:
cleanup_stuff()
Nhor answered 2020-07-11T12:40:36Z
1 votes
这是您问题的最直接解决方案。 我使用在finally块中检查file的习惯用法。
顺便说一句,您应该知道file是Python类名,因此您应该选择其他变量名。
file = None
try:
file = open(filePath, 'w')
except IOError:
msg = ("Unable to create file on disk.")
file.close()
return
finally:
if file != None:
file.write("Hello World!")
file.close()
stackoverflowuser2010 answered 2020-07-11T12:41:01Z
0 votes
最终,即使发生异常,也总是在“结尾”处被调用。 您可以使用它来确保关闭打开的资源(例如,数据库连接,文件等)。
我认为您误解了语义。
您的逻辑应该在“ try”中,应该在“ except”块中处理异常,并且无论您的方法如何终止,“ finally”都将执行,请使用它进行清理。
pcalcao answered 2020-07-11T12:41:29Z
-2 votes
始终建议在try块中编写可能引发异常的逻辑或代码,并使用finally块关闭资源。
Rohit Goyal answered 2020-07-11T12:41:49Z