欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

对python中的try、except、finally 执行顺序详解

程序员文章站 2023-08-12 13:16:23
如下所示: def test1(): try: print('to do stuff') raise exception('hehe')...

如下所示:

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)
   return i
   finally:
   i += 1
 print ('i in finally : %s'%i )

print('test3return : %s'% test3())

输出:

i in try : 1
i in except : 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())

输出

i in finally : 2
test4return : 1

test3和test4得到的结论:

在except和try中遇到return时,会锁定return的值,然后跳转到finally中,如果finally中没有return语句,则finally执行完毕之后仍返回原return点,将之前锁定的值返回(即finally中的动作不影响返回值),如果finally中有return语句,则执行finally中的return语句。

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()

输出

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得到的结论:

在一个循环中,最终要跳出循环之前,会先转到finally执行,执行完毕之后才开始下一轮循环

以上这篇对python中的try、except、finally 执行顺序详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。