首頁  >  文章  >  後端開發  >  圖文詳解python異常處理方法

圖文詳解python異常處理方法

高洛峰
高洛峰原創
2017-03-23 14:42:531844瀏覽

python提供了兩個非常重要的功能來處理python程式在運行中出現的異常和錯誤。你可以使用該功能來調試python程式。

我們可開啟idle-->F1進行檢視文檔,裡面很多異常類型,如圖:

圖文詳解python異常處理方法

什麼是異常?

異常即是一個事件,該事件會在程式執行過程中發生,影響了程式的正常執行。

一般情況下,在Python無法正常處理程序時就會發生一個異常。

異常是Python對象,表示一個錯誤。

當Python腳本發生異常時我們需要捕獲處理它,否則程式會終止執行。

異常處理

捕捉異常可以使用 try/except 語句。

try/except語句用來偵測try語句區塊中的錯誤,讓except語句捕捉異常訊息並處理。

如果你不想在異常發生時結束你的程序,只需在try裡捕獲它。

語法:

以下為簡單的try....except...else的語法:

try :

        #執行別的程式碼

#except 

        如果在try部份引發了'name'異常

except ,:

        #如果引發了'name'異常,獲得附加的資料

#else:

#        ##如果沒有例外發生

try的工作原理是,當開始一個try語句後,python就在目前程式的上下文中作標記,這樣當例外出現時就可以回到這裡,try子句先執行,接下來會發生什麼依賴執行時是否出現異常。

如果當try後的語句執行時發生異常,python就跳回try並執行第一個符合該異常的except子句,異常處理完畢,控制流就通過整個try語句(除非在處理異常時又引發新的異常)。

#如果在try後的語句裡發生了異常,卻沒有匹配的except子句,異常將被遞交到上層的try,或者到程序的最上層(這樣將結束程序,並打印缺省的出錯訊息)。

#如果在try子句執行時沒有發生異常,python會執行else語句後的語句(如果有else的話),然後控制流通過整個try語句。

實例

下面是簡單的例子,它打開一個文件,在該文件中的內容寫入內容,且並未發生異常:

#!/usr/bin/python

#try:

##   fh = open(#"testfile"#, "w")

#   fh.write("This is my test file for exception handling!!"#)

except IOError:

##### ###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/python

try:

   fh = open(" testfile""r")

   #fh .write("This is my test file for exception handling!!")

#except

#IOError:   

print

 ##   print 

##   

print "Error: can\'t find file or read data"

else

:

#   #print  "Written content in the file successfully"

以上程式輸出結果:

#Error : can't find fileor 

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.#############以上方式try-except語句捕捉所有發生的例外。但這不是一個很好的方式,我們不能透過該程式識別出具體的異常訊息。因為它捕獲所有的異常。 ######使用except而帶多種異常類型######你也可以使用相同的except語句來處理多個異常訊息,如下所示:########### #try######:##################   ######You do your operations here;############ #######   ######......................##########

except(Exception1[, Exception2[,...ExceptionN]]]):

##If there is any exception from #the given exception  #the given exception 

#list

   then execute this block.

#   ......................

#else:

   

If there 

is

 no exception then execute this block.#try-finally 語句

try-finally 語句無論是否發生例外狀況都會執行最後的程式碼。

try

:

#

finally:

#    

##退出try時總是會執行

raise

#注意:你可以使用except語句或者finally語句,但是兩者不能同時使用。 else語句也不能與finally語句同時使用#!/usr/bin/python

#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"如果開啟的檔案沒有可寫權限,輸出如下:

Error: can't find

file

 or read data

同樣的例子也可以寫成如下:##!/usr/bin/python

#try:   fh = open(

"testfile"

"w")

   try#:

      

#fh.write( #)

   

#finally:

      

print "Going to close the file"

##      #      

####   )##################except### ###IOError:#########

   print "Error: can\'t find file or read data"

當在try區塊中拋出一個異常,立即執行finally區塊程式碼。

finally區塊中的所有語句執行後,異常被再次提出,並執行except區塊程式碼。

參數的內容不同於異常。

異常的參數

一個異常可以帶參數,可作為輸出的例外訊息參數。

你可以透過except語句來捕捉例外的參數,如下所示:

#:

   You do your operations here;

   #..... ....................

except ExceptionType, Argument:

   You can print value of Argument here...

value of Argument here...

#變數接收的異常值通常包含在異常的語句中。在元組的表單中變數可以接收一個或多個值。

元組通常包含錯誤字串,錯誤數字,錯誤位置。

實例以下為單一例外的實例:

#!/usr/bin/python

# Define a function here.def

 

temp_convert(var):#   try

:      # return int

(var)   except

 

ValueError, 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 foro#() with base 10##'xyz'

#觸發異常

我們可以使用raise語句自己觸發例外

raise語法格式如下:raise [Exception [, args [, traceback]]]

#語句中Exception是異常的類型(例如,NameError)參數是一個異常參數值。此參數是可選的,如果不提供,異常的參數是"None"。

最後一個參數是可選的(在實踐中很少使用),如果存在,則是追蹤異常物件。

實例

一個異常可以是一個字串,類別或物件。 Python的核心提供的異常,大多數都是實例化的類,這是一個類別的實例的參數。

定義一個例外非常簡單,如下:def functionName( level ):

#   if level <code>1:

######################################################################

      raise "Invalid level!"##, level

, level

      # The code below to this would not be executed

##  

##注意:為了能夠捕獲異常,"except"語句必須有用相同的異常來拋出類別物件或字串。 例如我們捕捉以上異常,"except"語句如下所示:

try:

   Business Logic here...

except "Invalid level!" :

   

Exception handling here...

else

:

   Rest of the code here...

##使用者自訂異常透過建立一個新的異常類,程式可以命名它們自己的異常。異常應該是典型的繼承自Exception類,透過直接或間接的方式。 以下為與RuntimeError相關的實例,實例中建立了一個類,基底類別為RuntimeError,用於在異常觸發時輸出更多的資訊。 在try語句區塊中,使用者自訂的例外後執行except區塊語句,變數 e 是用來建立Networkerror類別的實例。

class Networkerror(RuntimeError):

   def __init__(self

, arg):##################      #######self# #####.args ######=### ###arg#############在你定義以上類別後,可以觸發這個異常,如下圖所示: ############try######:###################   ######raise### ## #Networkerror(######"Bad hostname"######)##################except### ###Networkerror,e:# #################   ######print### ###e.args########

以上是圖文詳解python異常處理方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn