標籤:python標準異常、異常處理、try...except...finnally try...except...escel
在我們編寫指令碼或者進行軟體開發過程中總會遇見很多的異常和錯誤,而python裡面有兩個非常重要的功能,能夠很好的處理異常和任何意外錯誤,這兩個功能就是異常處理和斷言。
異常處理:主要包含語法錯誤和其他的標準異常,標準異常介紹如下表。
斷言:斷言是一種理智檢查,當程式的測試完成,你可以開啟或關閉。斷言的最簡單的方法就是把它比作 raise-if 語句 (或者更準確,加 raise-if-not 聲明). 一個運算式進行測試,如果結果出現 false,將引發異常。斷言是由 assert 語句,在Python中新的關鍵字,在Python1.5版本中引入使用的關鍵字。
程式員常常放置斷言來檢查輸入的有效,或在一個函數調用後檢查有效輸出。
一、標準異常表
異常名稱 |
描述 |
| Exception |
所有異常的基類 |
| StopIteration |
當一個迭代器的 next()方法不指向任何對象時引發 |
| SystemExit |
由 sys.exit()函數引發 |
| StandardError |
除了StopIteration異常和SystemExit,所有內建異常的基類 |
| ArithmeticError |
數值計算所發生的所有錯誤的基類 |
| OverflowError |
當數字類型計算超過最高限額引發 |
| FloatingPointError |
當一個浮點運算失敗時觸發 |
| ZeroDivisonError |
當除運算或模零在所有數實值型別運算時引發 |
| AssertionError |
Assert 陳述式失敗的情況下引發 |
| AttributeError |
屬性引用或賦值失敗的情況下引發 |
| EOFError |
當從 input() 函數輸入,到達檔案末尾時觸發 |
| ImportError |
當一個 import 語句失敗時觸發 |
| KeyboardInterrupt |
當使用者中斷程式執行,通常是通過按 Ctrl+c 引發 |
| LookupError |
所有尋找錯誤基類 |
IndexError KeyError |
當在一個序列中沒有找到一個索引時引發 當指定的鍵沒有在字典中找到引發 |
| NameError |
當在局部或全域命名空間中找不到的標識引發 |
UnboundLocalError EnvironmentError |
試圖訪問在函數或方法的局部變數時引發,但沒有值分配給它。 Python環境之外發生的所有異常的基類。 |
IOError IOError |
當一個輸入/輸出操作失敗,如列印語句或 open()函數試圖開啟不存在的檔案時引發 作業系統相關的錯誤時引發 |
SyntaxError IndentationError |
當在Python語法錯誤引發; 沒有正確指定縮排引發。 |
| SystemError |
當解譯器發現一個內部問題,但遇到此錯誤時,Python解譯器不退出引發 |
| SystemExit |
當Python解譯器不使用sys.exit()函數引發。如果代碼沒有被處理,解譯器會退出。 |
|
當操作或函數在指定資料類型無效時引發 |
| ValueError |
在內建函數對於資料類型,參數的有效類型時引發,但是參數指定了無效值 |
| RuntimeError |
當產生的錯誤不屬於任何類別時引發 |
| NotImplementedError |
當要在繼承的類來實現,抽象方法實際上沒有實現時引發此異常 |
異常樣本:
1、FileNotFoundError嘗試開啟文d:\\openstack.txt檔案由於檔案不存在就會報出FIleNotFoundError:f=open("d:\\openstack.txt")Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> f=open("d:\\openstack.txt")FileNotFoundError: [Errno 2] No such file or directory: ‘d:\\openstack.txt‘2、ZeroDivisionError除法運算或模數運算中,除數為零的情況 >>> 5/0Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> 5/0ZeroDivisionError: division by zero3、ImportError一般是在匯入模組時,由於模組不存在等原因導致報錯>>> import wwwwTraceback (most recent call last): File "<pyshell#2>", line 1, in <module> import wwwwImportError: No module named ‘wwww‘4、ValueError 一般是由於傳入參數的資料類型錯誤引起報錯。 >>> a="sterc">>> int(a)Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> int(a)ValueError: invalid literal for int() with base 10: ‘sterc‘>>>
二、異常處理
python中包含兩種異常處理語句,可以使用try...except...finally或者try...except..else語句來處理異常,接下來簡單的介紹兩種語句的文法以及兩者的區別:
try語句原理:
首先,執行try子句(在關鍵字try和關鍵字except之間的語句)
如果沒有異常發生,忽略except子句,try子句執行後結束。
如果在執行try子句的過程中發生了異常,那麼try子句餘下的部分將被忽略。如果異常的類型和 except 之後的名稱相符,那麼對應的except子句將被執行。最後執行 try 語句之後的代碼。
如果一個異常沒有與任何的except匹配,那麼這個異常將會傳遞給上層的try中。
一個 try 語句可能包含多個except子句,分別來處理不同的特定的異常。最多隻有一個分支會被執行。
處理常式將只針對對應的try子句中的異常進行處理,而不是其他的 try 的處理常式中的異常。
一個except子句可以同時處理多個異常,這些異常將被放在一個括弧裡成為一個元組。
try...except..else文法:
try: You do your operations here ......................except ExceptionI: If there is ExceptionI, then execute this block.except ExceptionII: If there is ExceptionII, then execute this block. ......................else: If there is no exception then execute this block. 單個 try 語句可以有多個except語句。 當 try 塊包含可能拋出不同類型的異常聲明這是有用的也可以提供一個通用的 except 子句來處理異常(不提倡)except子句後,可以包括 else 子句。 如果代碼在try:塊不引發異常則代碼在 else 塊執行else是可以正常運行部存在異常的代碼,這不需要 try: 塊的保護 try: fh = open("testfile", "w+") fh.write("This is my test file for exception handling!!")except IOError: print ("Error: can\‘t find file or read data")else: print ("Written content in the file successfully") fh.close() 正常執行後就會產生testfile檔案裡面的內容為:This is my test file for exception handling! 而控制台輸出結果如下: Written content in the file successfully
用except子句處理多個異常
剛才我們的樣本是處理了一個類型的異常,而except可以處理多個類型的異常例如
except(ValueError,ImportError,RuntimeError)這是可以將多個類型的標準錯誤寫成一個元組,但是做個類型容易造成我們隊類型的報錯分析難度大。
try: fh = open("testfile", "r") fh.write("This is my test file for exception handling!!")except (ValueError,ImportError,RuntimeError): print ("Error: can\‘t find file or read data")else: print ("Written content in the file successfully") fh.close() 結果: Error: can‘t find file or read data #這裡沒有報出是那個類型的標準錯誤。try-finally子句:
使用 try: 塊. finally 塊是必須執行,而不管 try 塊是否引發異常或沒有。try-finally 語句的文法是這樣的。
try: You do your operations here; ...................... Due to any exception, this may be skipped.
except ExceptionI: If there is ExceptionI, then execute this block.except ExceptionII: If there is ExceptionII, then execute this block.
finally:
This would always be executed.
try...except...finally無論try塊能否正常的執行,finally是一定會執行的模組。
try: fh = open("testfile", "r") fh.write("This is my test file for exception handling!!")except (ValueError,ImportError,RuntimeError): print ("Error: can\‘t find file or read data")finally: print ("Written content in the file successfully") fh.close() #關閉檔案 結果:檔案中沒有寫入內容, 控制台輸出以下內容:Error: can‘t find file or read dataWritten content in the file successfully
引發異常
可以通過使用 raise 語句觸發幾個方面的異常。對於 raise 語句的一般文法如下。
文法
raise [Exception [, args [, traceback]]]
這裡,Exception 是異常的類型(例如,NameError)argument 為異常的參數值。該參數是可選的;如果沒有提供,異常的參數是None。
最後一個參數 traceback,也可選的(實踐中很少使用),並且如果存在的話,是用於異常的回溯對象。
樣本
異常可以是一個字串,一個類或一個對象。大多數Python的異常核心是觸發類異常,使用類的一個執行個體參數的異常。定義新的異常是很容易的,可以按如下做法 -
def functionName( level ): if level <1: raise Exception(level) # The code below to this would not be executed # if we raise the exception return level
注意:為了捕捉異常,一個“except”語句必須是指出拋出類對象異常或簡單的字串異常。例如,捕獲異常上面,我們必須編寫 except 子句如下 -
try: Business Logic here...except Exception as e: Exception handling here using e.args...else: Rest of the code here...
下面的例子說明如何使用觸發異常:
#!/usr/bin/python3def functionName( level ): if level <1: raise Exception(level) # The code below to this would not be executed # if we raise the exception return leveltry: l=functionName(-10) print ("level=",l)except Exception as e: print ("error in level argument",e.args[0])
這將產生以下結果
error in level argument -10
使用者定義的異常
Python中,還可以通過內建的異常標準的衍生類別來建立自己的異常。
這裡是關於 RuntimeError 的一個例子。這裡一個類被建立,它是 RuntimeError 的子類。當需要時,一個異常可以捕獲用來顯示更具體的資訊,這非常有用。
在try塊,使用者定義的異常將引發,並夾在 except 塊中。 變數e是用來建立網路錯誤 Networkerror 類的執行個體。
class Networkerror(RuntimeError): def __init__(self, arg): self.args = arg
所以上面的類定義後,可以引發異常如下 -
try: raise Networkerror("Bad hostname")except Networkerror,e: print e.args
本文出自 “堅持夢想” 部落格,請務必保留此出處http://dreamlinux.blog.51cto.com/9079323/1911106
Python 標準異常總結