我不知道为什么我们最终需要尝试……最后陈述。在我看来,这个代码块

try:
    run_code1()
except TypeError:
    run_code2()
other_code()

和这个finally的用法一样:

try:
    run_code1()
except TypeError:
    run_code2()
finally:
    other_code()

我遗漏了什么吗?


当前回答

在这里你可以看到如何尝试,除了,否则,最终一起工作。实际上,由于您的代码没有'else',那么您所声称的是正确的。也就是说,你写的两个语句之间没有区别。但是如果在某个地方使用了'else',那么'finally'就有区别了

其他回答

在第一个例子中,如果run_code1()引发了一个不是TypeError的异常,会发生什么?... Other_code()将不会被执行。

与finally: version: other_code()相比,无论引发任何异常,都保证执行。

您可以使用finally来确保无论是否发生异常都关闭或释放文件或资源,即使您没有捕获异常。(或者如果你没有捕捉到特定的异常。)

myfile = open("test.txt", "w")

try:
    myfile.write("the Answer is: ")
    myfile.write(42)   # raises TypeError, which will be propagated to caller
finally:
    myfile.close()     # will be executed before TypeError is propagated

在本例中,您最好使用with语句,但这种结构也可以用于其他类型的资源。

几年后,我写了一篇关于滥用finally的博客文章,读者可能会觉得很有趣。

完美的例子如下:

try:
    #x = Hello + 20
    x = 10 + 20 
except:
    print 'I am in except block'
    x = 20 + 30
else:
    print 'I am in else block'
    x += 1
finally:
    print 'Finally x = %s' %(x)

为了让Abhijit Sahu对这个答案的评论更好看,并突出显示语法:

像这样,你可以观察到在以下情况下哪个代码块发生了什么:

try: 
    x = Hello + 20 
    x = 10 + 20 
except: 
    print 'I am in except block' 
    x = 20 + 30 
else: 
    print 'I am in else block' 
    x += 1 
finally: 
    print 'Finally x = %s' %(x) 

在这里你可以看到如何尝试,除了,否则,最终一起工作。实际上,由于您的代码没有'else',那么您所声称的是正确的。也就是说,你写的两个语句之间没有区别。但是如果在某个地方使用了'else',那么'finally'就有区别了