標籤:doc turn print function color 聲明 with faq class
捕獲異常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")ZeroDivisionError
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.fileException 常見錯誤類
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=911 def test():12 global x13 print(x)14 x =115 16 test()
UnboundLocalError
官方解釋法:
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 1011 works, but this code:12 13 >>>14 >>> x = 1015 >>> def foo():16 ... print x17 ... x += 118 results in an UnboundLocalError:19 20 >>>21 >>> foo()22 Traceback (most recent call last):23 ...24 UnboundLocalError: local variable ‘x‘ referenced before assignment25 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 = 1031 >>> def foobar():32 ... global x33 ... print x34 ... x += 135 >>> foobar()36 1037 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 x41 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 pass12 else:13 raise MyException("自訂錯誤")14 except MyException as e:15 print(e)自訂異常
python——異常類型