標籤: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語句 引發 異常。
還得指明錯誤/異常的名稱和伴隨異常 觸發的 異常對象。
可以引發的錯誤或異常應該分別是一個Error或Exception類的直接或間接匯出類。
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