Python 中 finally 關鍵字
在任何程式語言中,我們都會遇到需要引發異常的情況。Python 有許多內建異常處理機制。這些異常名稱處理了錯誤。Python 還有一個名為 finally 的塊,無論異常是否得到處理都會執行該塊。
語法
try: # main python Code.... except: # It is optional block # Code to handle exception finally: # This Code that is always executed
示例
在以下程式碼中,我們看到一個名為 NameError 的異常。在這裡,我們建立一個引用未宣告變數的程式碼。即使異常得到處理,程式碼仍然會進入 "finally" 塊。此外,"finally" 塊中的程式碼也會得到執行。
try:
var1 = 'Tutorials'
# NameError is raised
print(var2)
# Handle the exception
except NameError:
print("variable is not found in local or global scope.")
finally:
# Regardless of exception generation,
# this block is always executed
print('finally block code here')輸出
執行以上程式碼可得到以下結果:−
variable is not found in local or global scope. finally block code here
不帶異常處理
假設我們設計的程式碼不處理異常。即使這樣,finally 塊也會為未處理的異常執行程式碼。
示例
try:
var1 = 'Tutorials'
# NameError is raised
print(var2)
# No exception handling
finally:
# Regardless of exception generation,
# this block is always executed
print('finally block code here')輸出
執行以上程式碼可得到以下結果:−
finally block code here Traceback (most recent call last): File "xxx.py", line 4, in print(var2) NameError: name 'var2' is not defined
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP