对对python中的中的try、、except、、finally 执行顺序详解执行顺序详解
如下所示:如下所示:
def test1():
try:
print('to do stuff')
raise Exception('hehe')
print('to return in try')
return 'try'
except Exception:
print('process except')
print('to return in except')
return 'except'
finally:
print('to return in finally')
return 'finally'
test1Return = test1()
print('test1Return : ' + test1Return)
输出:
to do stuff
process except
to return in except
to return in finally
test1Return : finally
在 try 中 raise一个异常,就立刻转入 except 中执行,在except 中遇到 return 时,就强制转到 finally 中执行, 在 finally 中遇
到 return 时就返回
def test2():
try:
print('to do stuff')
print('to return in try')
return 'try'
except Exception:
print('process except')
print('to return in except')
return 'except'
finally:
print('to return in finally')
return 'finally'
test2Return = test2()
print('test1Return : ' + test2Return)
输出:
to do stuff
to return in try
to return in finally
test2Return : finally
这里在 try 中没有抛出异常,因此不会转到 except 中,但是在try 中遇到return时,也会立即强制转到finally中执行,并在
finally中返回
test1和和test2得到的结论:得到的结论:
无论是在try还是在except中,遇到return时,只要设定了finally语句,就会中断当前的return语句,跳转到finally中执行,如果
finally中遇到return语句,就直接返回,不再跳转回try/excpet中被中断的return语句
def test3():
i = 0
try:
i += 1
print('i in try : %s'%i)
raise Exception('hehe')
except Exception:
i += 1
print('i in except : %s'%i)
评论10
最新资源