捕獲異常try...except...finally...else
python為高級語言,就是通過try...except...finally...else機制來處理錯誤。
讓我們來看一下這段錯誤代碼:
1 try: 2 print("try...") 3 s = 10/0 #異常,之后代碼不執行 4 print("not run this code") 5 except ZeroDivisonError as e: #有錯誤執行一下語句 6 print("except",e) 7 finally: 8 print("finally...") # 有沒有錯誤都要執行finally;此處可以不加 9 print("END")
try下加入要執行代碼,如果代碼某處發生錯誤,錯誤之后代碼段不執行直接跳到except捕獲的錯誤類型拋出錯誤提示,最后走finally執行完畢,這里finally可有可無。else沒有錯誤發生時執行。
如果你不知道執行代碼段可能發生什么種類的錯誤,可以捕獲全部錯誤,比如:
1 try: 2 f = open("unexsit.file","r") 3 f.read() 4 except Exception as e: 5 print("出錯了,但是什么類型呢,打印一下吧",e) 6 7 #[Errno 2] No such file or directory: unexsit.file
常見錯誤類
AttributeError 不存在屬性
IoError 輸入或輸出異常
ImportError 無法引入模塊或包。(一般是路徑問題或模塊名稱有誤)
IndentationError 語法錯誤(SyntaxError子類),一般是代碼縮進錯誤
KeyError 字典中不存在關鍵字
KeyboardInterrupt Ctrl+C被按下
NameError 使用一個未被賦予對象的變量
SyntaxError 語法錯誤
TypeError 傳入對象類型與要求不符
UnboundLocalError 變量作用域的問題(詳見:https://docs.python.org/2/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value)
1 x=9 2 3 def test(): 4 print(x)# 5 x =1#python從上到下解釋,會吧x當做局部變量,然而上邊print要打印未聲明的局部變量,報錯 6 7 test() 8 #UnboundLocalError: local variable 'x' referenced before assignment 9 //修改 10 x=9 11 def test(): 12 global x 13 print(x) 14 x =1 15 16 test()
官方解釋法:
1 It can be a surprise to get the UnboundLocalError in previously working code when it is modified by adding an assignment statement somewhere in the body of a function. 2 3 This code: 4 5 >>> 6 >>> x = 10 7 >>> def bar(): 8 ... print x 9 >>> bar() 10 10 11 works, but this code: 12 13 >>> 14 >>> x = 10 15 >>> def foo(): 16 ... print x 17 ... x += 1 18 results in an UnboundLocalError: 19 20 >>> 21 >>> foo() 22 Traceback (most recent call last): 23 ... 24 UnboundLocalError: local variable 'x' referenced before assignment 25 This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since the last statement in foo assigns a new value to x, the compiler recognizes it as a local variable. Consequently when the earlier print x attempts to print the uninitialized local variable and an error results. 26 27 In the example above you can access the outer scope variable by declaring it global: 28 29 >>> 30 >>> x = 10 31 >>> def foobar(): 32 ... global x 33 ... print x 34 ... x += 1 35 >>> foobar() 36 10 37 This explicit declaration is required in order to remind you that (unlike the superficially analogous situation with class and instance variables) you are actually modifying the value of the variable in the outer scope: 38 39 >>> 40 >>> print x 41 11
ValueError 傳入不期望值
自定義異常
自定義異常通過繼承異常基類的方法的派生類。(好繞嘴)如下:
1 class MyException(Exception): 2 def __init__(self,name): 3 self.msg = name 4 5 def __str__(self): 6 return self.msg # 可以不重寫,繼承基類 7 8 #調用 9 try: 10 if flag: 11 pass 12 else: 13 raise MyException("自定義錯誤") 14 except MyException as e: 15 print(e)
