詳解在Python中處理異常的教程

來源:互聯網
上載者:User
什麼是異常?

異常是一個事件,其中一個程式,破壞程式的指令的正常流的執行過程中而發生的。一般情況下,當一個Python指令碼遇到一些情況不能處理,就拋出一個異常。異常是一個Python對象,它表示一個錯誤。

當Python指令碼拋出一個異常,它必須處理異常,否則將立即終止。
處理異常:

如果有可能會引發異常的一些可疑的代碼,就可以通過將可疑的代碼在一個try塊:保衛你的程式。在try塊,包括以下情況except:語句,其次是代碼,作為優雅的處理問題,儘可能塊。
文法

這裡是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語句可以有多個不同的語句。當try塊中包含可能會引發不同類型的異常語句,這是很有用的。
  • 也可以提供一個通用的except子句,它用來處理任何異常。
  • except子句後,可以包括其他子句。塊沒有引發異常:在別的塊中的代碼,如果在try中的代碼執行。
  • 在else塊是不需要try:塊的代碼的保護。

例子

這裡是簡單的例子,這將開啟一個檔案並寫入內容的檔案中並移出正常:

#!/usr/bin/pythontry:  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/pythontry:  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子句無異常:

還可以使用不同的定義如下無異常的聲明:

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 語句捕獲所有出現的異常。使用這種try-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:塊。在try塊是否引發異常或沒有任何代碼 finally塊是一個必須執行的塊。try-finally語句的文法是這樣的:

try:  You do your operations here;  ......................  Due to any exception, this may be skipped.finally:  This would always be executed.  ......................

請注意,可以提供except子句或finally子句,但不能同時使用。不能同時使用else子句與finally子句。
例子:

#!/usr/bin/pythontry:  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/pythontry:  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 語句如果出現在一個更高的層在try-except語句。
Exception參數:

異常可以有一個參數,參數是一個值,它給出了關於這個問題的其他資訊。參數按異常內容改變。可以通過不同的子句提供一個變數,如下所示捕獲異常的參數:

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 numbersinvalid literal for int() with base 10: 'xyz'

拋出異常:

可以通過使用raise語句拋出幾個方面的異常。一般raise語句的文法。
文法

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

這裡,Exception是異常的類型(例如,NameError)和參數是用於異常的參數值。該參數是可選的;如果未提供,則異常的參數是None。

最後一個參數traceback,也是可選的(並且在實踐中很少使用),並且如果存在的話,那麼用於異常回溯對象。
例子:

異常可以是一個字串,一個類或一個對象。大多數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...

使用者定義的異常:

Python中,還可以通過內建的異常標準的衍生類別來建立自己的異常。

下面是有關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.