python——異常類型

來源:互聯網
上載者:User

標籤: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.file
Exception 常見錯誤類

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——異常類型

聯繫我們

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