我不知道为什么我们最终需要尝试……最后陈述。在我看来,这个代码块
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()
我遗漏了什么吗?
当前回答
try块只有一个强制子句:try语句。 except、else和finally子句是可选的,基于用户的首选项。
最后: 在Python离开try语句之前,它将在任何条件下运行finally块中的代码,即使它正在结束程序。例如,如果Python在except或else块中运行代码时遇到错误,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块将是多余的。
如果你早点回来,情况就不一样了:
try:
run_code1()
except TypeError:
run_code2()
return None # The finally block is run before the method returns
finally:
other_code()
与此相比:
try:
run_code1()
except TypeError:
run_code2()
return None
other_code() # This doesn't get run if there's an exception.
其他可能导致差异的情况:
如果在except块内抛出异常。 如果在run_code1()中抛出异常,但它不是TypeError。 其他控制流语句,如continue和break语句。
试着先运行这段代码,不要使用finally块,
1 / 0导致除零误差。
try:
1 / 0
print(1)
except Exception as e:
1 / 0
print(e)
然后尝试运行这段代码,
try:
1 / 0
print(1)
except Exception as e:
1 / 0
print(e)
finally:
print('finally')
对于第一种情况,你没有finally块, 因此,当在except块中发生错误时,程序执行将停止,并且在except块之后不能执行任何东西。
但对于第二种情况, 错误发生,但在程序停止之前,python先执行finally块,然后导致程序停止。 这就是为什么你要用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)
在这里你可以看到如何尝试,除了,否则,最终一起工作。实际上,由于您的代码没有'else',那么您所声称的是正确的。也就是说,你写的两个语句之间没有区别。但是如果在某个地方使用了'else',那么'finally'就有区别了