python中的異常

來源:互聯網
上載者:User

標籤:位置   txt   直接   rup   解釋   個人   bre   代碼   assert   

什麼是異常

所謂異常,就是程式運行時發生的錯誤訊號,在程式出現錯誤時,則會產生一個異常。如果程式沒有處理它,則會拋出異常,程式也會隨之終止。

下面是一個產生異常的例子:

上面說了程式出現錯誤則會產生異常,而錯誤又分為兩種:

#語法錯誤示範一if#語法錯誤示範二def test:    pass#語法錯誤示範三class Foo    pass#語法錯誤示範四print(haha# 這種錯誤,根本過不了python解譯器的文法檢測,必須在程式執行前就改正
語法錯誤
#TypeError:int類型不可迭代for i in 3:    pass#ValueErrornum=input(">>: ") #輸入helloint(num)#NameErroraaa#IndexErrorl=[‘11‘,‘aa‘]l[3]#KeyErrordic={‘name‘:‘老王‘}dic[‘age‘]#AttributeErrorclass Foo:passFoo.x#ZeroDivisionError:無法完成計算res1=1/0res2=1+‘str‘
邏輯錯誤 常見的異常
AttributeError 試圖訪問一個對象沒有的樹形,比如foo.x,但是foo沒有屬性xIOError 輸入/輸出異常;基本上是無法開啟檔案ImportError 無法引入模組或包;基本上是路徑問題或名稱錯誤IndentationError 語法錯誤(的子類) ;代碼沒有正確對齊IndexError 下標索引超出序列邊界,比如當x只有三個元素,卻試圖訪問x[5]KeyError 試圖訪問字典裡不存在的鍵KeyboardInterrupt Ctrl+C被按下NameError 使用一個還未被賦予對象的變數SyntaxError Python代碼非法,代碼不能編譯(個人認為這是語法錯誤,寫錯了)TypeError 傳入物件類型與要求的不符合UnboundLocalError 試圖訪問一個還未被設定的局部變數,基本上是由於另有一個同名的全域變數,導致你以為正在訪問它ValueError 傳入一個調用者不期望的值,即使值的類型是正確的

 關於異常並沒有列舉完,唯寫出常見的幾種,還有產生它們可能的原因。

異常處理

一個誤區

一想到異常,很多人只想到了try...except,這並不正確。

如果錯誤發生的條件是可以預測的,我們就有用if進行處理,在錯誤發生之前進行預防。

AGE=10while True:    age=input(‘>>: ‘).strip()    if age.isdigit(): #只有在age為字串形式的整數時,下列代碼才不會出錯,該條件是可預知的        age=int(age)        if age == AGE:            print(‘you got it‘)            break
View Code

 如果錯誤發生的條件是不可預測的,則需要用try...except,在錯誤發生之後進行處理。

#基本文法為try:    被檢測的代碼塊except 異常類型:    try中一旦檢測到異常,就執行這個位置的邏輯#舉例try:    f=open(‘a.txt‘)    g=(line.strip() for line in f)    print(next(g))    print(next(g))    print(next(g))    print(next(g))    print(next(g))except StopIteration:    f.close()
View Code

 關於異常處理需要瞭解的:

#1 異常類只能用來處理指定的異常情況,如果非指定異常則無法處理。s1 = ‘hello‘try:    int(s1)except IndexError as e: # 未捕獲到異常,程式直接報錯    print e#2 多分支s1 = ‘hello‘try:    int(s1)except IndexError as e:    print(e)except KeyError as e:    print(e)except ValueError as e:    print(e)#3 萬能異常Exceptions1 = ‘hello‘try:    int(s1)except Exception as e:    print(e)#4 多分支異常與萬能異常#4.1 如果你想要的效果是,無論出現什麼異常,我們統一丟棄,或者使用同一段代碼邏輯去處理他們,那麼騷年,大膽的去做吧,只有一個Exception就足夠了。#4.2 如果你想要的效果是,對於不同的異常我們需要定製不同的處理邏輯,那就需要用到多分支了。#5 也可以在多分支後來一個Exceptions1 = ‘hello‘try:    int(s1)except IndexError as e:    print(e)except KeyError as e:    print(e)except ValueError as e:    print(e)except Exception as e:    print(e)#6 異常的其他機構s1 = ‘hello‘try:    int(s1)except IndexError as e:    print(e)except KeyError as e:    print(e)except ValueError as e:    print(e)#except Exception as e:#    print(e)else:    print(‘try內代碼塊沒有異常則執行我‘)finally:    print(‘無論異常與否,都會執行該模組,通常是進行清理工作‘)#7 主動觸發異常try:    raise TypeError(‘類型錯誤‘)except Exception as e:    print(e)#8 自訂異常class EgonException(BaseException):    def __init__(self,msg):        self.msg=msg    def __str__(self):        return self.msgtry:    raise EgonException(‘類型錯誤‘)except EgonException as e:    print(e)#9 斷言:assert 條件assert 1 == 1  assert 1 == 2#10 總結try..except1:把錯誤處理和真正的工作分開來2:代碼更易組織,更清晰,複雜的工作任務更容易實現;3:毫無疑問,更安全了,不至於由於一些小的疏忽而使程式意外崩潰了;

 

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.