我不知道为什么我们需要finally在try...except...finally声明中.在我看来,这个代码块
try:
run_code1()
except TypeError:
run_code2()
other_code()
Run Code Online (Sandbox Code Playgroud)
与使用finally以下内容相同:
try:
run_code1()
except TypeError:
run_code2()
finally:
other_code()
Run Code Online (Sandbox Code Playgroud)
我错过了什么吗?
是else和finally异常处理部分多余的?例如,以下两个代码段之间有什么区别吗?
try:
foo = open("foo.txt")
except IOError:
print("error")
else:
print(foo.read())
finally:
print("finished")
Run Code Online (Sandbox Code Playgroud)
和
try:
foo = open("foo.txt")
print(foo.read())
except IOError:
print("error")
print("finished")
Run Code Online (Sandbox Code Playgroud)
更一般地说,不能将内容else总是移入try,而不能将内容finally移到try/catch块之外?如果是这样,是什么目的else和finally?它只是为了增强可读性吗?
当我放入finally子句时,raise语句 inexcept不起作用。
所以except块不会产生Exception.
我错过了什么?如果我想重新提高Exceptionafterfinally子句返回值,我需要做什么?
def test():
res = 1
try:
raise Exception
res = 2
except:
print('ha fallado')
raise
finally:
return res
test()
Run Code Online (Sandbox Code Playgroud)
解决方案:
def test():
res = 1
try:
raise Exception
res = 2
except:
print('ha fallado')
raise
finally:
# ... finally code that need to exec
pass
return res
print(test())
Run Code Online (Sandbox Code Playgroud)
这样,如果发生异常,except 块会处理该异常,然后引发它。
如果没有发生异常,则返回该值。
感谢所有的答案!这么快 :)