finally中return的注意点

今天在finally语句上栽了坑,具体是这样的:

def foo():
    try:
        raise Exception
    except Exception as e:
        print 'b'
        raise
    finally:
        print 'a'

foo()

这个代码的输出是:

[/tmp]$python x.py 
b
a
Traceback (most recent call last):
  File "x.py", line 10, in <module>
    foo()
  File "x.py", line 3, in foo
    raise Exception
Exception

如果在finally中加上return:

def foo():
    try:
        raise Exception
    except Exception as e:
        print 'b'
        raise
    finally:
        print 'a'
        return 0

foo()

那么except中的raise就不会向上传递异常:

[/tmp]$python x.py 
b
a

对于这种要return的,可以把return放在finally的后面:

def foo():
    try:
        raise Exception
    except Exception as e:
        print 'b'
        raise
    finally:
        print 'a'
    return 0

foo()

发表评论

电子邮件地址不会被公开。 必填项已用*标注

*