try:
Put the possible error code here
except Exception as e:
Put... Here try When something unusual happens , Code that handles exceptions
else:
Put... Here try The code that continues to execute without exception
finally:
Here is the code that will be executed no matter whether there is an exception in the code
As a python beginner , My exception handling finally Very interested
No matter what try Whether the block causes an error , Will always be implemented finally block
At first it seems that there is nothing wrong
For example, the following code :
def add_num():
try:
num1 = 1
num2 = 0
res = num1 / num2
print(f' The result is :{
res}')
except Exception as e:
print(f" Something went wrong , The type of error is :{
e}")
finally:
print("add_num The function is finished ")
print(add_num())
# Something went wrong , The type of error is :division by zero
# add_num The function is finished
# None
But if except sentence Inside print Turned into return, What will happen
We know that we encounter return The program is over , But look at the code below , Something strange happened
def add_num():
try:
num1 = 1
num2 = 0
res = num1 / num2
except Exception as e:
return f" Something went wrong , The type of error is :{
e}"
finally:
print("add_num The function is finished ")
print(add_num())
# add_num The function is finished
# Something went wrong , The type of error is :division by zero
Encountered in exception handling return I even skipped , Run to execute finally The sentence in , At the end of the day return
In this case , I'm confused , I specially checked the information , Just understand why
No matter in front try and except What about? ,python Will guarantee finally The statement of must be executed !
Python All the designs of are centered on this core idea , This is what I'm doing with all my efforts .
therefore , front try Clause (clause), perhaps except Clause, if there is an exception that will cause the program to terminate , such as return, that python I will seal this first , wait until finally Throw the exception after execution
So you can see the exception in finally After the output result , No surprise ?