我不知道为什么我们最终需要尝试……最后陈述。在我看来,这个代码块
try:
run_code1()
except TypeError:
run_code2()
other_code()
和这个finally的用法一样:
try:
run_code1()
except TypeError:
run_code2()
finally:
other_code()
我遗漏了什么吗?
我不知道为什么我们最终需要尝试……最后陈述。在我看来,这个代码块
try:
run_code1()
except TypeError:
run_code2()
other_code()
和这个finally的用法一样:
try:
run_code1()
except TypeError:
run_code2()
finally:
other_code()
我遗漏了什么吗?
当前回答
为了补充上面的其他答案,无论发生什么,finally子句都会执行,而else子句只在没有引发异常时执行。
例如,写入一个没有异常的文件将输出以下内容:
file = open('test.txt', 'w')
try:
file.write("Testing.")
print("Writing to file.")
except IOError:
print("Could not write to file.")
else:
print("Write successful.")
finally:
file.close()
print("File closed.")
输出:
Writing to file.
Write successful.
File closed.
如果存在异常,代码将输出以下内容(注意,故意使文件保持只读会导致错误。
file = open('test.txt', 'r')
try:
file.write("Testing.")
print("Writing to file.")
except IOError:
print("Could not write to file.")
else:
print("Write successful.")
finally:
file.close()
print("File closed.")
输出:
Could not write to file.
File closed.
我们可以看到,无论异常如何,finally子句都会执行。希望这能有所帮助。
其他回答
下面是一段代码来澄清两者的区别:
...
try:
a/b
print('In try block')
except TypeError:
print('In except block')
finally:
print('In finally block')
print('Outside')
A b = 0,1
输出:
In try block
In finally block
Outside
(没有错误,除了跳过块。)
A b = 1,0
输出:
In finally block
Traceback (most recent call last):
a/b
ZeroDivisionError: division by zero
(没有为ZeroDivisionError指定异常处理,只执行finally块。)
A, b = 0, '1'
输出:
In except block
In finally block
Outside
(异常被正确处理,程序没有中断。)
注意:如果你有一个except块来处理所有类型的错误,finally块将是多余的。
在第一个例子中,如果run_code1()引发了一个不是TypeError的异常,会发生什么?... Other_code()将不会被执行。
与finally: version: other_code()相比,无论引发任何异常,都保证执行。
代码块是不等效的。如果run_code1()抛出TypeError以外的异常,或者run_code2()抛出异常,finally子句也将运行,而第一个版本中的other_code()在这些情况下不会运行。
最后是“清理行动”的定义。finally子句在离开try语句之前的任何事件中执行,无论是否发生异常(即使您没有处理它)。
我赞同拜尔斯的例子。
在这里你可以看到如何尝试,除了,否则,最终一起工作。实际上,由于您的代码没有'else',那么您所声称的是正确的。也就是说,你写的两个语句之间没有区别。但是如果在某个地方使用了'else',那么'finally'就有区别了