異常處理:主要包含語法錯誤和其他的標準異常,標準異常介紹如下表。
斷言:斷言是一種理智檢查,當程序的測試完成,你可以打開或關(guān)閉。斷言的最簡單的方法就是把它比作 raise-if 語句 (或者更準確,加 raise-if-not 聲明). 一個表達式進行測試,如果結(jié)果出現(xiàn) false,將引發(fā)異常。斷言是由 assert 語句,在Python中新的關(guān)鍵字,在Python1.5版本中引入使用的關(guān)鍵字。
程序員常常放置斷言來檢查輸入的有效,或在一個函數(shù)調(diào)用后檢查有效的輸出。
一、標準異常表
異常示例:
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 除法運算或取模運算中,除數(shù)為零的情況 >>> 5/0 Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> 5/0 ZeroDivisionError: division by zero 3、ImportError 一般是在導入模塊時,由于模塊不存在等原因?qū)е聢箦e >>> import wwww Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> import wwww ImportError: No module named 'wwww' 4、ValueError 一般是由于傳入?yún)?shù)的數(shù)據(jù)類型錯誤引起報錯。 >>> 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語句來處理異常,接下來簡單的介紹兩種語句的語法以及兩者的區(qū)別:
try語句原理:
首先,執(zhí)行try子句(在關(guān)鍵字try和關(guān)鍵字except之間的語句)
如果沒有異常發(fā)生,忽略except子句,try子句執(zhí)行后結(jié)束。
如果在執(zhí)行try子句的過程中發(fā)生了異常,那么try子句余下的部分將被忽略。如果異常的類型和 except 之后的名稱相符,那么對應(yīng)的except子句將被執(zhí)行。最后執(zhí)行 try 語句之后的代碼。
如果一個異常沒有與任何的except匹配,那么這個異常將會傳遞給上層的try中。
一個 try 語句可能包含多個except子句,分別來處理不同的特定的異常。最多只有一個分支會被執(zhí)行。
處理程序?qū)⒅会槍?yīng)的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:塊不引發(fā)異常則代碼在 else 塊執(zhí)行 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() 正常執(zhí)行后就會生成testfile文件里面的內(nèi)容為:This is my test file for exception handling! 而控制臺
用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() 結(jié)果: Error: can't find file or read data #這里沒有報出是那個類型的標準錯誤。
try-finally子句:
使用 try: 塊. finally 塊是必須執(zhí)行,而不管 try 塊是否引發(fā)異常或沒有。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塊能否正常的執(zhí)行,finally是一定會執(zhí)行的模塊。
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() #關(guān)閉文件 結(jié)果:文件中沒有寫入內(nèi)容, 控制臺
引發(fā)異常
可以通過使用 raise 語句觸發(fā)幾個方面的異常。對于 raise 語句的一般語法如下。
語法
raise [Exception [, args [, traceback]]]
這里,Exception 是異常的類型(例如,NameError)argument 為異常的參數(shù)值。該參數(shù)是可選的;如果沒有提供,異常的參數(shù)是None。
最后一個參數(shù) traceback,也可選的(實踐中很少使用),并且如果存在的話,是用于異常的回溯對象。
示例
異常可以是一個字符串,一個類或一個對象。大多數(shù)Python的異常核心是觸發(fā)類異常,使用類的一個實例參數(shù)的異常。定義新的異常是很容易的,可以按如下做法 -
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...
下面的例子說明如何使用觸發(fā)異常:
#!/usr/bin/python3 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 try: l=functionName(-10) print ("level=",l) except Exception as e: print ("error in level argument",e.args[0])
這將產(chǎn)生以下結(jié)果
error in level argument -10
用戶定義的異常
Python中,還可以通過內(nèi)置的異常標準的派生類來創(chuàng)建自己的異常。
這里是關(guān)于 RuntimeError 的一個例子。這里一個類被創(chuàng)建,它是 RuntimeError 的子類。當需要時,一個異常可以捕獲用來顯示更具體的信息,這非常有用。
在try塊,用戶定義的異常將引發(fā),并夾在 except 塊中。 變量e是用來創(chuàng)建網(wǎng)絡(luò)錯誤 Networkerror 類的實例。
class Networkerror(RuntimeError): def __init__(self, arg): self.args = arg
所以上面的類定義后,可以引發(fā)異常如下 -
try: raise Networkerror("Bad hostname") except Networkerror,e: print e.args
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com