This is quite interesting, let’s run a few codes first
1. This code means that you don’t have to worry about how many layers of try you have. In fact, you just need to figure out why exceptions are not thrown under except
2. This code means that if finally has a return statement, no exception will be thrown, and if there is no return, an exception will be thrown
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
3. I checked it out and saw this article on in-depth understanding of Python’s finally
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
4. At this time, are you more clear about finally~
Learn now and sell now. If there are any errors, please point out and correct them~
This is quite interesting, let’s run a few codes first
1. This code means that you don’t have to worry about how many layers of try you have. In fact, you just need to figure out why exceptions are not thrown under except
2. This code means that if finally has a return statement, no exception will be thrown, and if there is no return, an exception will be thrown
3. I checked it out and saw this article on in-depth understanding of Python’s finally
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
4. At this time, are you more clear about finally~
Learn now and sell now. If there are any errors, please point out and correct them~
If an exception is thrown in the end, isn’t your except statement in vain?