Python學習--異常

來源:互聯網
上載者:User

標籤:元組   trace   程式   rac   基類   多個   說明   enter   lang   

一、定義

Python用異常對象來表示異常情況。遇到錯誤後,會引發異常,如果異常對象並沒有被處理或者捕捉,程式就會用所謂的回溯(traceback)終止執行。

每個異常都是一些類的執行個體,這些執行個體可以被引發,並且可以用很多方法進行捕捉。

 

二、raise語句引發異常

>>> raise ExceptionTraceback (most recent call last):File "<stdin>", line 1, in <module>Exception>>> raise Exception(‘error error‘)Traceback (most recent call last):File "<stdin>", line 1, in <module>Exception: error error

Exception是所有異常類的基類。其它一些常見異常類可以查看手冊。上面兩個例子都通過raise語句引發了異常。第二個例子裡加上了錯誤資訊。

 

三、捕捉異常

通過try/except語句可以實現捕捉異常的功能。針對具體的異常,可以在except後面加上異常類,如下:

try:   x = input(‘Enter the first number: ‘)   y = input(‘Enter the second number: ‘)   print x/yexcept ZeroDiyisionError:   print "the second number can‘t be zero! "

如果except後面什麼異常類也不加,那麼就會捕捉所有異常。

如果捕捉到了異常又想重新引發它,可以調用不帶參數的raise。

try:    x = input(‘Enter the first number: ‘)    y = input(‘Enter the second number: ‘)    print x/yexcept ZeroDiyisionError:    raise 

四、捕捉多個異常

第一種方法可以使用多個except子句,針對每種情況說明。

try:    x = input(‘Enter the first number: ‘)    y = input(‘Enter the second number: ‘)    print x/yexcept ZeroDiyisionError:    print "the second number can‘t be zero! "except TypeError:    print "That was‘t a number!
當然也可以將異常類型作為元組列出。
try:    x = input(‘Enter the first number: ‘)    y = input(‘Enter the second number: ‘)    print x/yexcept (TypeError, NameError):    print "Your numbers were bogus..."

 

五、訪問異常對象本身

try:    x = input(‘Enter the first number: ‘)    y = input(‘Enter the second number: ‘)    print x/yexcept (TypeError, NameError),e:    print e

通過如上方式就可以將錯誤列印出來。

 

六、使用else 、finally語句

在捕捉異常的時候,也可以聯合使用else、finally語句來執行一些操作。

x = Nonetry:    x = 1/0except NameError:    print "Unknown variable"else: #無異常時會執行else語句    print "That went well!"finally: #不管是否有異常,都會執行finally語句    print "Cleaning up"?

 

Python學習--異常

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.