|
Python提供了兩個(gè)非常重要的功能來(lái)處理Python程序中的異常和錯(cuò)誤,并在其中添加調(diào)試的函數(shù)功能 : 異常處理 : 在本教程中介紹。這是一個(gè)列表標(biāo)準(zhǔn)Python中提供的異常 : 標(biāo)準(zhǔn)異常。 斷言 : 在Python 3教程中的斷言中介紹。 標(biāo)準(zhǔn)異常以下是Python中可用的標(biāo)準(zhǔn)異常列表 :
Python中的斷言斷言是一個(gè)健全檢查,可以在完成對(duì)程序的測(cè)試后打開(kāi)或關(guān)閉。 試想斷言的最簡(jiǎn)單的方法就是將它與一個(gè)raise:if語(yǔ)句(或者更準(zhǔn)確的說(shuō)是一個(gè)加注if語(yǔ)句)相對(duì)應(yīng)。測(cè)試表達(dá)式,如果結(jié)果為false,則會(huì)引發(fā)異常。 斷言由版本1.5引入的assert語(yǔ)句來(lái)執(zhí)行,它是Python的最新關(guān)鍵字。 程序員經(jīng)常在函數(shù)開(kāi)始時(shí)放置斷言來(lái)檢查有效的輸入,并在函數(shù)調(diào)用后檢查有效的輸出。 assert語(yǔ)句當(dāng)它遇到一個(gè)assert語(yǔ)句時(shí),Python會(huì)評(píng)估求值它的的表達(dá)式,是否為所希望的那樣。 如果表達(dá)式為false,Python會(huì)引發(fā)AssertionError異常。 assert的語(yǔ)法是 : assert Expression[, Arguments]12復(fù)制代碼類(lèi)型:[python] 如果斷言失敗,Python將使用ArgumentExpression作為AssertionError的參數(shù)。 使用try:except語(yǔ)句可以像任何其他異常一樣捕獲和處理AssertionError異常。 如果沒(méi)有處理,它們將終止程序并產(chǎn)生回溯。 示例 這里將實(shí)現(xiàn)一個(gè)功能:將給定的溫度從開(kāi)爾文轉(zhuǎn)換為華氏度。如果是負(fù)溫度,該功能將退出 : #!/usr/bin/python3def KelvinToFahrenheit(Temperature): assert (Temperature >= 0),"Colder than absolute zero!" return ((Temperature-273)*1.8)+32print (KelvinToFahrenheit(273))print (int(KelvinToFahrenheit(505.78)))print (KelvinToFahrenheit(-5))12345678910復(fù)制代碼類(lèi)型:[python] 當(dāng)執(zhí)行上述代碼時(shí),會(huì)產(chǎn)生以下結(jié)果 : 32.0451Traceback (most recent call last): File "test.py", line 9, in <module>print KelvinToFahrenheit(-5) File "test.py", line 4, in KelvinToFahrenheitassert (Temperature >= 0),"Colder than absolute zero!"AssertionError: Colder than absolute zero!123456789復(fù)制代碼類(lèi)型:[python] 什么是異常?一個(gè)例外是在程序執(zhí)行期間發(fā)生的一個(gè)事件,它破壞程序指令的正常流程。 一般來(lái)說(shuō),當(dāng)Python腳本遇到無(wú)法應(yīng)對(duì)的情況時(shí),會(huì)引發(fā)異常。異常是一個(gè)表示錯(cuò)誤的Python對(duì)象。 當(dāng)Python腳本引發(fā)異常時(shí),它必須立即處理異常,否則終止并退出。 處理異常如果有一些可能引發(fā)異常的可疑代碼,可以通過(guò)將可疑代碼放在try:塊中來(lái)保護(hù)您的程序。 在try:塊之后,包括一個(gè)except:語(yǔ)句,然后是一個(gè)盡可能優(yōu)雅地處理問(wèn)題的代碼塊。 語(yǔ)法 下面是簡(jiǎn)單的語(yǔ)法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.1234567891011復(fù)制代碼類(lèi)型:[python] 以下是上述語(yǔ)法的幾個(gè)重點(diǎn) : 一個(gè)try語(yǔ)句可以有多個(gè)except語(yǔ)句。 當(dāng)try塊包含可能引發(fā)不同類(lèi)型的異常的語(yǔ)句時(shí),這就很有用。 還可以提供一個(gè)通用的except子句,它處理任何異常。 在except子句之后,可以包含一個(gè)else子句。 如果try:block中的代碼不引發(fā)異常,則else塊中的代碼將執(zhí)行。 else:block是一個(gè)不需要try:block保護(hù)的代碼的地方。 示例 此示例打開(kāi)一個(gè)文件,將內(nèi)容寫(xiě)入文件,并且優(yōu)雅地出現(xiàn),因?yàn)橥耆珱](méi)有問(wèn)題 : #!/usr/bin/python3try:
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()12345678910復(fù)制代碼類(lèi)型:[python]這產(chǎn)生以下結(jié)果 : Written content in the file successfully1復(fù)制代碼類(lèi)型:[python] 示例 此示例嘗試打開(kāi)一個(gè)沒(méi)有寫(xiě)入權(quán)限的文件,因此它引發(fā)了一個(gè)異常 : #!/usr/bin/python3try:
fh = open("testfile", "r")
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")1234567891011復(fù)制代碼類(lèi)型:[python]這產(chǎn)生以下結(jié)果 : Error: can't find file or read data1復(fù)制代碼類(lèi)型:[python] except子句沒(méi)有指定異常也可以使用except語(yǔ)句,但不定義異常,如下所示 : try: You do your operations here ......................except: If there is any exception, then execute this block. ......................else: If there is no exception then execute this block.123456789復(fù)制代碼類(lèi)型:[python] 這種try:except語(yǔ)句捕獲所有發(fā)生的異常。使用這種try:except語(yǔ)句不被認(rèn)為是一個(gè)很好的編程實(shí)踐,因?yàn)樗东@所有異常,但不會(huì)讓程序員能更好地識(shí)別發(fā)生的問(wèn)題的根本原因。 except子句指定多個(gè)異常還可以使用相同的except語(yǔ)句來(lái)處理多個(gè)異常,如下所示: try: You do your operations here ......................except(Exception1[, Exception2[,...ExceptionN]]]): If there is any exception from the given exception list, then execute this block. ......................else: If there is no exception then execute this block.12345678910復(fù)制代碼類(lèi)型:[python] try:finally子句可以使用finally:塊和try:塊。 finally:塊是放置必須執(zhí)行代碼的地方,無(wú)論try塊是否引發(fā)異常。 try:finally語(yǔ)句的語(yǔ)法是這樣的 : try: You do your operations here; ...................... Due to any exception, this may be skipped.finally: This would always be executed. ......................1234567復(fù)制代碼類(lèi)型:[python] 注意 : 可以提供except子句或finally子句,但不能同時(shí)提供。不能使用else子句以及finally子句。 示例 #!/usr/bin/python3try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")finally: print ("Error: can\'t find file or read data")
fh.close()12345678復(fù)制代碼類(lèi)型:[python]如果沒(méi)有以寫(xiě)入形式打開(kāi)文件的權(quán)限,則會(huì)產(chǎn)生以下結(jié)果 : Error: can't find file or read data1復(fù)制代碼類(lèi)型:[python] 同樣的例子可以寫(xiě)得更干凈如下 : #!/usr/bin/python3try:
fh = open("testfile", "w") try:
fh.write("This is my test file for exception handling!!") finally: print ("Going to close the file")
fh.close()except IOError: print ("Error: can\'t find file or read data")123456789101112復(fù)制代碼類(lèi)型:[python]當(dāng)try塊中拋出異常時(shí),執(zhí)行將立即傳遞給finally塊。 在finally塊中的所有語(yǔ)句都被執(zhí)行之后,異常被再次引發(fā),如果存在于try:except語(yǔ)句的下一個(gè)更高的層中,則在except語(yǔ)句中處理異常。 異常參數(shù)一個(gè)異常可以有一個(gè)參數(shù),參數(shù)它是一個(gè)值,它提供有關(guān)該問(wèn)題的其他信息。 參數(shù)的內(nèi)容因異常而異。 可以通過(guò)在except子句中提供變量來(lái)捕獲異常的參數(shù),如下所示: try: You do your operations here ......................except ExceptionType as Argument: You can print value of Argument here...12345復(fù)制代碼類(lèi)型:[python] 如果編寫(xiě)代碼來(lái)處理單個(gè)異常,則可以在except語(yǔ)句中使用一個(gè)變量后跟異常的名稱(chēng)。 如果要捕獲多個(gè)異常,可以使用一個(gè)變量后跟隨異常的元組。 此變量接收大部分包含異常原因的異常值。 變量可以以元組的形式接收單個(gè)值或多個(gè)值。 該元組通常包含錯(cuò)誤字符串,錯(cuò)誤編號(hào)和錯(cuò)誤位置。 示例 以下是一個(gè)例外 : #!/usr/bin/python3# Define a function here.def temp_convert(var):
try: return int(var) except ValueError as Argument: print ("The argument does not contain numbers\n", Argument)# Call above function here.temp_convert("xyz")1234567891011復(fù)制代碼類(lèi)型:[python]這產(chǎn)生以下結(jié)果 : The argument does not contain numbers invalid literal for int() with base 10: 'xyz'123復(fù)制代碼類(lèi)型:[python] 拋出異常可以通過(guò)使用raise語(yǔ)句以多種方式引發(fā)異常。raise語(yǔ)句的一般語(yǔ)法如下 : 語(yǔ)法 raise [Exception [, args [, traceback]]]12復(fù)制代碼類(lèi)型:[python] 這里,Exception是異常的類(lèi)型(例如,NameError),args是異常參數(shù)的值。 參數(shù)是可選的; 如果沒(méi)有提供,則異常參數(shù)為None。 最后一個(gè)參數(shù)traceback也是可選的(在實(shí)踐中很少使用),如果存在,則是用于異常的追溯對(duì)象。 示例 異??梢允亲址?lèi)或?qū)ο蟆?Python核心引發(fā)的大多數(shù)異常都是類(lèi),一個(gè)參數(shù)是類(lèi)的一個(gè)實(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 level123456復(fù)制代碼類(lèi)型:[python] 注意 : 為了捕獲異常,“except”子句必須引用與類(lèi)對(duì)象或簡(jiǎn)單字符串相同的異常。例如,為了捕獲上述異常,必須寫(xiě)出except子句如下: try: Business Logic here...except Exception as e: Exception handling here using e.args...else: Rest of the code here...1234567復(fù)制代碼類(lèi)型:[python] 以下示例說(shuō)明了使用引發(fā)異常 : #!/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])123456789101112131415復(fù)制代碼類(lèi)型:[python]這將產(chǎn)生以下結(jié)果 : error in level argument -101復(fù)制代碼類(lèi)型:[python] 用戶(hù)定義的異常Python還允許通過(guò)從標(biāo)準(zhǔn)內(nèi)置異常導(dǎo)出類(lèi)來(lái)創(chuàng)建自己的異常。 這是一個(gè)與RuntimeError有關(guān)的示例。 在這里,從RuntimeError類(lèi)創(chuàng)建一個(gè)子類(lèi)。 當(dāng)需要在捕獲異常時(shí)顯示更多具體信息時(shí),這就很有用了。 在try塊中,用戶(hù)定義的異常被引發(fā)并被捕獲在except塊中。 變量e用于創(chuàng)建Networkerror類(lèi)的實(shí)例。 class Networkerror(RuntimeError): def __init__(self, arg): self.args = arg123復(fù)制代碼類(lèi)型:[python] 所以當(dāng)定義了上面的類(lèi)以后,就可以使用以下命令拋出異常 : try: raise Networkerror("Bad hostname")except Networkerror,e: print e.args
|
|
|
來(lái)自: 碼農(nóng)9527 > 《Python》