The execution sequence of try, sort T, and finally in python.
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)
Output:
To do stuff
Process failed t
To return in response t
To return in finally
Test1Return: finally
If a raise exception occurs in try, it is immediately transferred to wait t for execution. when return is encountered in wait t, it is forcibly transferred to finally for execution. If return is encountered in finally, it is returned.
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)
Output:
To do stuff
To return in try
To return in finally
Test2Return: finally
No exception is thrown in try, so it will not be transferred to counter T. However, when return is encountered in try, it will be immediately forced to be executed in finally and returned in finally.
Test1 and test2:
When a return statement is set in try or wait t, the current return statement is interrupted and jumped to finally for execution. If return statements are encountered in finally, return directly, instead of redirecting back to the interrupted return Statement in try/excpet
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)
return i
finally:
i += 1
print ('i in finally : %s'%i )
print('test3Return : %s'% test3())
Output:
I in try: 1
I in memory T: 2
I in finally: 3
Test3Return: 2
def test4():
i = 0
try:
i += 1
return i
finally:
i += 1
print ('i in finally : %s'%i )
print('test4Return : %s' % test4())
Output
I in finally: 2
Test4Return: 1
Test3 and test4:
The return value will be locked when return is encountered in wait t and try, and then jump to finally. If there is no return statement in finally, the original return point will still be returned after finally execution is complete, return the previously locked value (that is, the action in finally does not affect the return value). If there is a return statement in finally, the return Statement in finally is executed.
def test5():
for i in range(5):
try:
print('do stuff %s'%i)
raise Exception(i)
except Exception:
print('exception %s'%i)
continue
finally:
print('do finally %s'%i)
test5()
Output
Do stuff 0
Exception 0
Do finally 0
Do stuff 1
Exception 1
Do finally 1
Do stuff 2
Exception 2
Do finally 2
Do stuff 3
Exception 3
Do finally 3
Do stuff 4
Exception 4
Do finally 4
Test5 concluded that:
In a loop, before the loop is finally exceeded, it is first transferred to finally for execution. After the execution is completed, the next loop starts.