1. 程式人生 > 其它 >Python學習筆記之異常處理

Python學習筆記之異常處理

技術標籤:Python學習筆記python

Python異常處理

_ try _except語句

try:
    f = open("hello.txt", 'r')
    f.write("這是一個測試檔案")
# 注意: except語句不一定會執行, 只有在try語句中出現IOError報錯時, 才會執行.
except IOError as e:
    print('異常:',e)
# 如果沒有捕獲到異常, 則執行else語句的內容
else:
    print("檔案內容寫入成功")
# 無論是否捕獲到異常, 都執行的語句.
finally: f.close() print("檔案已經關閉")

在這裡插入圖片描述
不指定異常型別的except使用

try:
    f = open('hello.txt')
    # f.write("這是一個測試檔案")
    f.write('cooffee')
# 不建議捕獲所有的異常, 因能不能定位錯誤的位置.
except:
    print("捕獲所有的異常....")
else:
    print("如果沒有捕獲到異常, 執行else語句")
finally:
    f.close(
) print("有異常或者沒有異常都會執行")

在這裡插入圖片描述
捕獲多個異常

try:
    d = dict(a=1, b=2)
    print(d['f'])  # KeyError
    print(a)  # NameError
except (KeyError, NameError) as e:
    print(e)
else:
    print("沒有產生異常")
finally:
    print("無論是否產生異常的操作")
print("new start")

在這裡插入圖片描述
Try … Finally


假設你正在你的讀取中讀取一份檔案。你應該如何確保檔案物件被正確關閉,無論是否會發生異常?這可以通過 finally 塊來完成。

import sys 
import time
f = None 
try:
    f = open("poem.txt") # 我們常用的檔案閱讀風格 
    while True:
        line = f.readline() 
        if len(line) == 0: 
        	break 
        print(line, end='')
        sys.stdout.flush()
        print("Press ctrl+c now") # 為了確保它能執行一段時間 
        time.sleep(2) 
 except IOError:
    print("Could not find file poem.txt") 
 except KeyboardInterrupt:
    print("!! You cancelled the reading from the file.") 
 finally: 
 	if f:
    	f.close()
    print("(Cleaning up: Closed the file)")
$ python exceptions_finally.py
Programming is fun
Press ctrl+c now
^C!! You cancelled the reading from the file.
(Cleaning up: Closed the file)

我們按照通常檔案讀取進行操作,但是我們同時通過使用 time.sleep 函式任意在每列印一行後插入兩秒休眠,使得程式執行變得緩慢(在通常情況下 Python 執行得非常快速)。當程式在處在執行過過程中時,按下 ctrl + c 來中斷或取消程式。

你會注意到 KeyboardInterrupt 異常被丟擲,爾後程式退出。不過,在程式退出之前,finally 子句得到執行,檔案物件總會被關閉。

另外要注意到我們在 print 之後使用了 sys.stout.flush(),以便它能被立即列印到螢幕上。

with 語句
在 try 塊中獲取資源,然後在 finally 塊中釋放資源是一種常見的模式。因此,還有一個 with 語句使得這一過程可以以一種乾淨的姿態得以完成。

with open("poem.txt") as f: 
	for line in f:
        print(line, end='')

程式輸出的內容應與上一個案例所呈現的相同。本例的不同之處在於我們使用的是 open 函式與 with 語句——我們將關閉檔案的操作交由 with open 來自動完成。

在幕後發生的事情是有一項 with 語句所使用的協議(Protocol)。它會獲取由 open 語句返回的物件,在本案例中就是“thefile”。

它總會在程式碼塊開始之前呼叫 thefile.enter 函式,並且總會在程式碼塊執行完畢之後呼叫 thefile.exit

因此,我們在 finally 程式碼塊中編寫的程式碼應該格外留心 exit 方法的自動操作。這能夠幫助我們避免重複顯式使用 try…finally 語句。

丟擲異常
raise: 關鍵字, 用來丟擲異常.
raise 丟擲異常的名稱, 丟擲異常的詳細顯示
自定義異常類

class ShortInputException(Exception):
 	'''一個由使用者定義的異常類''' 
 	def __init__(self, length, atleast): 
 		Exception.__init__(self)
        self.length = length
        self.atleast = atleast 
    try : 
    	text = input('Enter something --> ') 
        if len(text) < 3: 
        	raise ShortInputException(len(text), 3) # 其他工作能在此處繼續正常執行 
    except EOFError: 
        print('Why did you do an EOF on me?') 
    except ShortInputException as ex:
        print(('ShortInputException: The input was ' + '{0} long, expected at least {1}').format(ex.length, ex.atleast)) 
    elseprint('No exception was raised.')
$ python exceptions_raise.py
Enter something --> a
ShortInputException: The input was 1 long, expected at least 3

$ python exceptions_raise.py
Enter something --> abc
No exception was raised.

斷言assert
assert 語句 如果這個語句為真則通過,為假則報錯

def is_huiwen_num(num):
    snum = str(num)
    return snum == snum[::-1]
# 如果希望程式中的所有assert語句不執行, 那麼給python -O 指令碼名
if __name__ == "__main__":
    assert is_huiwen_num(100) == True, "error"
    assert  is_huiwen_num(101) == True
    print("assert")

在這裡插入圖片描述
(以上轉載自他人,便於自己學習記錄)