In [8]: def bar():
...: a = 10
...: try:
...: raise
...: except:
...: try:
...: raise
...: except:
...: raise
...: finally:
...: return a
In [9]: bar()
Out[9]: 10
天蓬老师2017-04-18 10:30:05
This is quite interesting, let’s run a few codes first
def bar():
a = 10
try:
print 1
raise
except:
print 2
raise
finally:
print 3
return a
bar()
# 打印(没有抛出异常):
# 2
# 3
def bar():
a = 10
try:
print 1
raise
except:
print 2
raise
finally:
print 3
# return a
bar()
# 打印(抛出了异常):
# 2
# Traceback (most recent call last):
# 3
# File "/Users/xuxin/workplace/DailyScript/segmentfault/file_list_to_dict.py", line 23, in <module>
# bar()
# File "/Users/xuxin/workplace/DailyScript/segmentfault/file_list_to_dict.py", line 18, in bar
# raise ValueError()
# ValueError
It seems that after f() throws an exception, it executes the return in except, but it does not return to the caller, but "persists" in executing the code in finally. At this point, I finally understand the true meaning of finally, which is that even if the return has been made, the code in finally must still be executed.
We can also understand here that if there is a statement that requires an exit method in try, it will try to execute finally. If finally has a return method, it will return immediately and the previous exit statement will not be executed.
At this time, we can take a look at this string of code
def bar():
a = 10
try:
print 1
raise
finally:
print 3
return a
bar()
# 打印(没有抛出异常):
# 3
Learn now and sell now. If there are any errors, please point out and correct them~
ringa_lee2017-04-18 10:30:05
If an exception is thrown in the end, isn’t your except statement in vain?