那年那日那朵花

".......(o´ω`o)......"

python中try和except以及finally的return顺序

2017-05-19 13:37 python

坑....直接看代码

#!/usr/bin/env python
#_*_ coding:utf-8 _*_
import traceback

def test1():
    try:
        a = "1231312"
        print a
        a / 3
        return 0
    except :
        print traceback.format_exc()
        return 1
    finally:
        print "fffff"
        #return 99


print test1()

输出为:

1231312
Traceback (most recent call last):
  File "C:\Users\hu\workspace\126\catchFinalReturnTest.py", line 9, in test1
    a / 3
TypeError: unsupported operand type(s) for /: 'str' and 'int'

fffff
1

另外一段代码

#!/usr/bin/env python
#_*_ coding:utf-8 _*_
import traceback

def test1():
    try:
        a = "1231312"
        print a
        a / 3
        return 0
    except :
        print traceback.format_exc()
        return 1
    finally:
        print "fffff"
        return 99


print test1()

输出为

1231312
Traceback (most recent call last):
  File "C:\Users\hu\workspace\126\catchFinalReturnTest.py", line 9, in test1
    a / 3
TypeError: unsupported operand type(s) for /: 'str' and 'int'

fffff
99

总结:try excepet 中如果执行下去需要return的时候会先执行finally中的代码段,然后在return。但是如果finally代码段中也有return,那么就会直接返回。这是坑。

或者这样

#!/usr/bin/env python
#_*_ coding:utf-8 _*_
import traceback

def test1():
    try:
        a = "1231312"
        print a
        a / 3
        c = 2
    except :
        print traceback.format_exc()
        c = 3
    finally:
        print "fffff"
        return c


print test1()

输出为

1231312
Traceback (most recent call last):
  File "C:\Users\hu\workspace\126\catchFinalReturnTest.py", line 9, in test1
    a / 3
TypeError: unsupported operand type(s) for /: 'str' and 'int'

fffff
3

Cloudhu 个人随笔|built by django|

沪ICP备16019452号-1