小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

關(guān)于Python異常處理,你要知道的事情!

 碼農(nóng)9527 2021-12-31

  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)異常列表 :

編號(hào)異常名稱(chēng)描述
1Exception所有異常的基類(lèi)
2StopIteration當(dāng)?shù)鞯?code style="box-sizing: border-box; margin: 0px; padding: 0px; border: 0px; font-style: inherit; font-variant: inherit; font-weight: inherit; font-stretch: inherit; line-height: inherit; font-family: SFMono-Regular, Consolas, "Liberation Mono", Menlo, Courier, monospace; font-size: 1em; white-space: pre;">next()方法沒(méi)有指向任何對(duì)象時(shí)引發(fā)。
3SystemExitsys.exit()函數(shù)引發(fā)。
4StandardErrorStopIterationSystemExit之外的所有內(nèi)置異常的基類(lèi)。
5ArithmeticError數(shù)據(jù)計(jì)算出現(xiàn)的所有錯(cuò)誤的基類(lèi)。
6OverflowError當(dāng)計(jì)算超過(guò)數(shù)字類(lèi)型的最大限制時(shí)引發(fā)。
7FloatingPointError當(dāng)浮點(diǎn)計(jì)算失敗時(shí)觸發(fā)。
8ZeroDivisonError對(duì)于所有的數(shù)字類(lèi)型,當(dāng)對(duì)零進(jìn)行除數(shù)或模數(shù)時(shí)產(chǎn)生。
9AssertionErrorAssert語(yǔ)句失敗的情況下引發(fā)。
10AttributeError在屬性引用或分配失敗的情況下引發(fā)。
11EOFError當(dāng)沒(méi)有來(lái)自raw_input()input()函數(shù)的輸入并且達(dá)到文件結(jié)尾時(shí)引發(fā)。
12ImportError導(dǎo)入語(yǔ)句失敗時(shí)引發(fā)。
13KeyboardInterrupt當(dāng)用戶(hù)中斷程序執(zhí)行時(shí),通常按Ctrl + c。
14LookupError所有查找錯(cuò)誤的基類(lèi)。
15IndexError當(dāng)序列中沒(méi)有找到索引時(shí)引發(fā)。
16KeyError當(dāng)在字典中找不到指定的鍵時(shí)引發(fā)。
17NameError當(dāng)在本地或全局命名空間中找不到標(biāo)識(shí)符時(shí)引發(fā)。
18UnboundLocalError當(dāng)嘗試訪(fǎng)問(wèn)函數(shù)或方法中的局部變量但未分配值時(shí)引發(fā)。
19EnvironmentError在Python環(huán)境之外發(fā)生的所有異常的基類(lèi)。
20IOError

在嘗試打開(kāi)不存在的文件時(shí),輸入/輸出操作失敗時(shí)觸發(fā),

例如print語(yǔ)句或open()函數(shù)。

21OSError引起操作系統(tǒng)相關(guān)的錯(cuò)誤。
22SyntaxError當(dāng)Python語(yǔ)法有錯(cuò)誤時(shí)引發(fā)。
23IndentationError當(dāng)縮進(jìn)未正確指定時(shí)觸發(fā)。
24SystemError

當(dāng)解釋器發(fā)現(xiàn)內(nèi)部問(wèn)題時(shí)引發(fā),但遇到此錯(cuò)誤時(shí),

Python解釋器不會(huì)退出。

25SystemExit

當(dāng)Python解釋器通過(guò)使用sys.exit()函數(shù)退出時(shí)引發(fā)。

如果沒(méi)有在代碼中處理,導(dǎo)致解釋器退出。

26TypeError在嘗試對(duì)指定數(shù)據(jù)類(lèi)型無(wú)效的操作或函數(shù)時(shí)引發(fā)。
27ValueError當(dāng)數(shù)據(jù)類(lèi)型的內(nèi)置函數(shù)具有有效參數(shù)類(lèi)型時(shí)引發(fā),但參數(shù)具有指定的無(wú)效值。
28RuntimeError產(chǎn)生的錯(cuò)誤不屬于任何類(lèi)別時(shí)引發(fā)。
29NotImplementedError當(dāng)需要在繼承類(lèi)中實(shí)現(xiàn)的抽象方法實(shí)際上沒(méi)有實(shí)現(xiàn)時(shí)引發(fā)。

  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

    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶(hù) 評(píng)論公約

    類(lèi)似文章 更多