異常處理: 這將在本教程所覆蓋講解。這是 Python 提供的標(biāo)準(zhǔn)異常的列表:標(biāo)準(zhǔn)異常
斷言: 這將在 Python3斷言教程覆蓋。
異常名稱
|
描述 |
---|---|
Exception |
所有異常的基類
|
StopIteration |
當(dāng)一個迭代器的 next()方法不指向任何對象時引發(fā)
|
SystemExit |
由 sys.exit()函數(shù)引發(fā)
|
StandardError |
除了StopIteration異常和SystemExit,所有內(nèi)置異常的基類
|
ArithmeticError |
數(shù)值計算所發(fā)生的所有錯誤的基類
|
OverflowError |
當(dāng)數(shù)字類型計算超過最高限額引發(fā)
|
FloatingPointError |
當(dāng)一個浮點運算失敗時觸發(fā)
|
ZeroDivisonError |
當(dāng)除運算或模零在所有數(shù)值類型運算時引發(fā)
|
AssertionError |
斷言語句失敗的情況下引發(fā)
|
AttributeError |
屬性引用或賦值失敗的情況下引發(fā)
|
EOFError |
當(dāng)從 raw_input() 與 input() 函數(shù)輸入,到達(dá)文件末尾時觸發(fā)
|
ImportError |
當(dāng)一個 import 語句失敗時觸發(fā)
|
KeyboardInterrupt |
當(dāng)用戶中斷程序執(zhí)行,通常是通過按 Ctrl+c 引發(fā)
|
LookupError |
所有查找錯誤基類
|
IndexError KeyError |
當(dāng)在一個序列中沒有找到一個索引時引發(fā)
當(dāng)指定的鍵沒有在字典中找到引發(fā)
|
NameError |
當(dāng)在局部或全局命名空間中找不到的標(biāo)識引發(fā)
|
UnboundLocalError EnvironmentError |
試圖訪問在函數(shù)或方法的局部變量時引發(fā),但沒有值分配給它。
Python環(huán)境之外發(fā)生的所有異常的基類。
|
IOError IOError |
當(dāng)一個輸入/輸出操作失敗,如打印語句或 open()函數(shù)試圖打開不存在的文件時引發(fā)
操作系統(tǒng)相關(guān)的錯誤時引發(fā)
|
SyntaxError IndentationError |
當(dāng)在Python語法錯誤引發(fā);
沒有正確指定縮進(jìn)引發(fā)。 |
SystemError |
當(dāng)解釋器發(fā)現(xiàn)一個內(nèi)部問題,但遇到此錯誤時,Python解釋器不退出引發(fā)
|
SystemExit | 當(dāng)Python解釋器不使用sys.exit()函數(shù)引發(fā)。如果代碼沒有被處理,解釋器會退出。 |
|
當(dāng)操作或函數(shù)在指定數(shù)據(jù)類型無效時引發(fā)
|
ValueError | 在內(nèi)置函數(shù)對于數(shù)據(jù)類型,參數(shù)的有效類型時引發(fā),但是參數(shù)指定了無效值 |
RuntimeError |
當(dāng)生成的錯誤不屬于任何類別時引發(fā)
|
NotImplementedError |
當(dāng)要在繼承的類來實現(xiàn),抽象方法實際上沒有實現(xiàn)時引發(fā)此異常
|
斷言的最簡單的方法就是把它比作 raise-if 語句 (或者更準(zhǔn)確,加 raise-if-not 聲明). 一個表達(dá)式進(jìn)行測試,如果結(jié)果出現(xiàn) false,將引發(fā)異常。
當(dāng)它遇到一個斷言語句,Python評估計算之后的表達(dá)式,希望是 true 值。如果表達(dá)式為 false,Python 觸發(fā) AssertionError 異常。
assert Expression[, Arguments]
如果斷言失敗,Python使用 ArgumentExpression 作為AssertionError異常的參數(shù)。AssertionError異??梢员徊东@,并用 try-except語句處理類似其他異常,但是,如果沒有處理它們將終止該程序并產(chǎn)生一個回溯。
這里是一個把從開氏度到華氏度的溫度轉(zhuǎn)換函數(shù)。
#!/usr/bin/python3 def KelvinToFahrenheit(Temperature): assert (Temperature >= 0),"Colder than absolute zero!" return ((Temperature-273)*1.8)+32 print (KelvinToFahrenheit(273)) print (int(KelvinToFahrenheit(505.78))) print (KelvinToFahrenheit(-5))
32.0 451 Traceback (most recent call last): File "test.py", line 9, in print KelvinToFahrenheit(-5) File "test.py", line 4, in KelvinToFahrenheit assert (Temperature >= 0),"Colder than absolute zero!" AssertionError: Colder than absolute zero!
異常是一個事件,這在程序的執(zhí)行過程中擾亂程序的指令的正常流程。一般來說,當(dāng)一個 Python 腳本遇到一種情況,它無法應(yīng)付則會引發(fā)一個異常。異常它是一個 Python 對象,它表示一個錯誤。
如果你有一些可疑的代碼,可能會引發(fā)異常, 可以通過將可疑代碼放在一個 try: 塊來保護(hù)你的程序。在 try:塊之后,包括 except: 語句隨后的代碼塊,作為優(yōu)雅的處理異常問題。
下面是 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語句。 當(dāng) try 塊包含可能拋出不同類型的異常聲明這是有用的
except子句后,可以包括 else 子句。 如果代碼在try:塊不引發(fā)異常則代碼在 else 塊執(zhí)行
#!/usr/bin/python3 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()
Written content in the file successfully
#!/usr/bin/python3 try: 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")
Error: can't find file or read data
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.
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.
可以使用 finally: 使用 try: 塊. finally 塊是必須執(zhí)行,而不管 try 塊是否引發(fā)異?;驔]有。try-finally 語句的語法是這樣的 -
try: You do your operations here; ...................... Due to any exception, this may be skipped. finally: This would always be executed. ......................
請注意,可以提供 except 子句,或 finally 子句,但不能同時使用。不能用一個 finally 子句中再使用 else 子句 。
#!/usr/bin/python3 try: 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()
Error: can't find file or read data
#!/usr/bin/python3 try: 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")
當(dāng)一個異常在try塊被拋出,立即執(zhí)行傳遞給 finally 塊。如果在 try-except 語句的下一個更高的層異常被再次引發(fā),并在處理 except 語句外。
異??梢杂幸粋€參數(shù),這是有關(guān)問題的其他信息的值。參數(shù)的內(nèi)容作為異常而都不太一樣??梢酝ㄟ^不同的子句中提供一個變量,如下所示捕獲異常參數(shù) -
try: You do your operations here ...................... except ExceptionType as Argument: You can print value of Argument here...
如果寫代碼來處理一個異常,可以使用一個變量按照異常的名稱在 except 語句中。 如果要捕捉多個異常,可以使用一個變量后跟一個異常的元組。
該變量接收大多含有異常的原因各種值。變量可以在一個元組的形式以接收一個或多個值。這個元組通常包含錯誤字符串,錯誤編號,以及錯誤位置。
#!/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")
The argument does not contain numbers invalid literal for int() with base 10: 'xyz'
可以通過使用 raise 語句觸發(fā)幾個方面的異常。對于 raise 語句的一般語法如下。
raise [Exception [, args [, 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...
#!/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])
error in level argument -10
這里是關(guān)于 RuntimeError 的一個例子。這里一個類被創(chuàng)建,它是 RuntimeError 的子類。當(dāng)需要時,一個異??梢圆东@用來顯示更具體的信息,這非常有用。
在try塊,用戶定義的異常將引發(fā),并夾在 except 塊中。 變量e是用來創(chuàng)建網(wǎng)絡(luò)錯誤 Networkerror 類的實例。
class Networkerror(RuntimeError): def __init__(self, arg): self.args = arg
try: raise Networkerror("Bad hostname") except Networkerror,e: print e.args