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

[Python tutorial] chapter 53 try... Except... Finally of exception handling

編輯:Python

In this article, we continue to learn Python exception handling , This paper mainly introduces try…except…finally Use of statements .

try…except…finally Statement Introduction

try…except The sentence can be in try Catch one or more exceptions in the branch and except Handle these exceptions in the branch . This statement also has an optional finally Branch :

try:
# Business code 
except:
# exception handling 
finally:
# Clean up the code 

Whether or not there is an exception , It will be carried out finally Code in branch .try Branch or any except Execute immediately after branch execution finally Branch .

The following flowchart demonstrates try…except…finally Statement execution :

try…except…finally Statement example

The following example uses try…except…finally sentence :

a = 10
b = 0
try:
c = a / b
print(c)
except ZeroDivisionError as error:
print(error)
finally:
print('Finishing up.')

The output is as follows :

division by zero
Finishing up.

In the example above ,try The branch produces a ZeroDivisionError abnormal , perform except The branch is followed by finally Branch .

In the following example try The branch did not generate an exception , So it's done try Branch and then execute finally Branch :

a = 10
b = 2
try:
c = a / b
print(c)
except ZeroDivisionError as error:
print(error)
finally:
print('Finishing up.')

The output is as follows :

5.0
Finishing up.

try…finally sentence

try…except…finally Statement except Branches can also be selected , So we can use :

try:
# Business code 
finally:
# Code that will always be executed 

Generally speaking , When we cannot handle exceptions but need to clean up resources, we can use this statement structure . for example , Whether there is an exception or not, you need to close the opened file .

summary

  • Whether or not there is an exception ,try…except…finally Statements are executed finally Statements in branches .
  • Use finally Branch cleanup resources , For example, closing a file .

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