鍍金池/ 教程/ Python/ Python3異常處理
Python3文件操作
Python3日期和時間
Python3基礎(chǔ)語法
Python3字典
Python3元組
Python3文件方法
Python3字符串
Python3引入什么新的東西?
Python3異常處理
Python3模塊
Python3數(shù)字
Python3變量類型
Python3函數(shù)
Python3循環(huán)
Python3 os文件目錄的方法
Python3 while循環(huán)語句
Python3斷言
Python3基本運算符
Python3環(huán)境安裝設(shè)置
Python3標(biāo)準(zhǔn)異常
Python3嵌套循環(huán)
Python3教程
Python3決策
Python3 for循環(huán)語句
Python3列表

Python3異常處理

Python提供了兩個非常重要的功能,以處理任何意外錯誤在你的Python程序,并在它們上面添加了調(diào)試功能 -
標(biāo)準(zhǔn)異常如下列表 -
異常名稱
描述
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ā)此異常

在Python中斷言

斷言是一種理智檢查,當(dāng)程序的測試完成,你可以打開或關(guān)閉。

斷言的最簡單的方法就是把它比作 raise-if 語句 (或者更準(zhǔn)確,加 raise-if-not 聲明). 一個表達(dá)式進(jìn)行測試,如果結(jié)果出現(xiàn) false,將引發(fā)異常。

斷言是由 assert 語句,在Python中新的關(guān)鍵字,在Python1.5版本中引入使用的關(guān)鍵字。
程序員常常放置斷言來檢查輸入的有效,或在一個函數(shù)調(diào)用后檢查有效的輸出。

assert 語句

當(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))
當(dāng)執(zhí)行上面的代碼,它產(chǎn)生以下結(jié)果 -
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 對象,它表示一個錯誤。

當(dāng) Python 腳本會引發(fā)一個異常,它必須要么處理異常,要么終止并退出。

處理異常

如果你有一些可疑的代碼,可能會引發(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. 
以下是有關(guān)上述語法幾個重要的地方 -
  • 單個 try 語句可以有多個except語句。 當(dāng) try 塊包含可能拋出不同類型的異常聲明這是有用的

  • 也可以提供一個通用的 except 子句來處理任何異常
  • except子句后,可以包括 else 子句。 如果代碼在try:塊不引發(fā)異常則代碼在 else 塊執(zhí)行

  • else 塊是代碼的好地方,這不需要 try: 塊的保護(hù)

示例

這個例子打開一個文件,并寫入內(nèi)容,文件處理完全沒有問題 -
#!/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()
這將產(chǎn)生以下結(jié)果 -
Written content in the file successfully

示例

這個例子試圖打開一個文件,如果沒有寫權(quán)限,它會拋出一個異常 -
#!/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")
這將產(chǎn)生以下結(jié)果 -
Error: can't find file or read data

except子句中無異常

也可以使用 except 語句定義如下無異常聲明如下 -
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. 

except子句與多個異常

也可以使用相同的 except 語句來處理多個異常,具體如下 -
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. 

try-finally子句

可以使用 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()
如果您沒有以寫入方式打開文件的權(quán)限,那么這將產(chǎn)生以下結(jié)果:
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ù)

異??梢杂幸粋€參數(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")
這將產(chǎn)生以下結(jié)果 -
The argument does not contain numbers
invalid literal for int() with base 10: 'xyz'

引發(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)置的異常標(biāo)準(zhǔn)的派生類來創(chuàng)建自己的異常。

這里是關(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
所以上面的類定義后,可以引發(fā)異常如下 -
try:
   raise Networkerror("Bad hostname")
except Networkerror,e:
   print e.args