python的finally语句中使用return要慎重!!!

前两天, 同事踩了一个坑, python代码的一个接口抛了异常, 但是返回值是0. 这里记录一下.

代码大概是这样的.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def division(a, b):
ret = 0

try:
ret = a / b
except Exception as e:
print('oops!')
raise e
finally:
return ret


try:
print(division(1, 0))
except Exception:
print('ooops!!')

# 运行一下, 结果如下.
> python3 test.py
oops!
0

是不是不符合你预期?

我们来改一行, 再看看

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def division(a, b):
ret = 0

try:
ret = a / b
except Exception as e:
print('oops!')
raise e
finally:
print('ops!') # 这行改了哦, 不用return了


try:
print(division(1, 0))
except Exception:
print('ooops!!')

# 运行一下, 结果如下.
> python3 test.py
oops!
ops!
ooops!!

现在的结果是不是符合预期了?

从这个采坑和测试过程来看, 在finally语句中一定要注意一下return的使用, 要慎重!!!