程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python exception handling finally

編輯:Python

python exception handling

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

about finally General explanation of function

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

Exception handling finally Correct and complete explanation

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 ?


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved