簡明Python教程學習筆記9

來源:互聯網
上載者:User

標籤:erro   ror   err   ctrl   語法錯誤   continue   color   define   .com   

13、異常

(1)錯誤

程式中的一些無效語句,比如語法錯誤,如下所示:

1 >>> Print "aa"2 SyntaxError: invalid syntax3 >>> print "aa"4 aa5 >>> 

(2)try...except

1 >>> s = raw_input("Enter something -->")2 Enter something -->#這裡期望輸入,但是實際執行了ctrl+d,導致了下面的異常3 4 Traceback (most recent call last):5   File "<pyshell#4>", line 1, in <module>6     s = raw_input("Enter something -->")7 EOFError: EOF when reading a line8 >>> 

可以使用try...except來處理異常

 1 # -*- coding:utf-8 -*- 2  3 import sys 4  5 try: 6     s = raw_input("Enter something -->") 7 except EOFError: 8     print "\nWhy did yo do an EOF on me?" 9     sys.exit()  # Exit the program10 except:11     print "\nSome error/exception occurred."12     # here, we are not exiting the program13 14 print "Done"

輸出:

(3)引發異常

可以使用raise語句 引發 異常

還得指明錯誤/異常的名稱和伴隨異常 觸發的 異常對象。

可以引發的錯誤或異常應該分別是一個ErrorException類的直接或間接匯出類。

 1 # -*- coding:utf-8 -*- 2  3  4 class ShortInputException(Exception): 5     """A user-defined exception class.""" 6  7     def __init__(self, length, atleast): 8         Exception.__init__(self) 9         self.length = length10         self.atleast = atleast11 12 13 try:14     s = raw_input("Enter something -->")15     if len(s) < 3:16         raise ShortInputException(len(s), 3)17         # other work can continue as usual here18 except EOFError:19     print "\nWhy did you do an EOF on me?"20 except ShortInputException, x:21     print "ShortInputException:The input was of length %d,was expecting at least %d" % (x.length, x.atleast)22 else:23     print "No exception was raised."

輸出:

(4)try...finally

希望在無論異常發生與否的情況下都執行某些操作,該怎麼做呢?

這可以使用finally塊來完成。

 

簡明Python教程學習筆記9

聯繫我們

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