python--異常處理,python異常

來源:互聯網
上載者:User

python--異常處理,python異常

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

我們可開啟idle-->F1進行查看文檔,裡面很多異常類型,

 

 

什麼是異常?

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

一般情況下,在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:     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  "Error: can\'t find file or read data" else :     print  "Written content in the file successfully" 以上程式輸出結果: 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.以上方式try-except語句捕獲所有發生的異常。但這不是一個很好的方式,我們不能通過該程式識別出具體的異常資訊。因為它捕獲所有的異常。使用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 語句

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( "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"

 

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

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

參數的內容不同於異常。

異常的參數

一個異常可以帶上參數,可作為輸出的異常資訊參數。

你可以通過except語句來捕獲異常的參數,如下所示:

try :     You do your operations here;     ...................... except  ExceptionType, Argument:     You can  print  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  for  int () with base  10 'xyz' 觸發異常

我們可以使用raise語句自己觸發異常

raise文法格式如下:

raise  [Exception [, args [, traceback]]] 

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

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

執行個體

一個異常可以是一個字串,類或對象。 Python的核心提供的異常,大多數都是執行個體化的類,這是一個類的執行個體的參數。

定義一個異常非常簡單,如下所示:

def  functionName( level ):     if  level <  1 :        raise  "Invalid level!" , level        # The code below to this would not be executed        # if we raise the exception 

注意:為了能夠捕獲異常,"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

 

       

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.