異常就是程序運行時發生錯誤的信號(在程序出現錯誤時,則會產生一個異常,若程序沒有處理它,則會拋出該異常,程序的運行也隨之終止),在python中,錯誤觸發的異常以下:python
而錯誤分紅兩種git
一、語法錯誤(這種錯誤,根本過不了python解釋器的語法檢測,必須在程序執行前就改正)編程
#語法錯誤示範一 if #語法錯誤示範二 def test: pass #語法錯誤示範三 class Foo pass #語法錯誤示範四 print(haha)
二、邏輯錯誤安全
#TypeError:int類型不可迭代 for i in 3: pass #ValueError num=input(">>: ") #輸入hello int(num) #NameError aaa #IndexError l=['egon','aa'] l[3] #KeyError dic={'name':'egon'} dic['age'] #AttributeError class Foo:pass Foo.x #ZeroDivisionError:沒法完成計算 res1=1/0 res2=1+'str'
在python中不一樣的異常能夠用不一樣的類型(python中統一了類與類型,類型即類)去標識,一個異常標識一種錯誤code
常見異常對象
AttributeError # 試圖訪問一個對象沒有的樹形,好比foo.x,可是foo沒有屬性x IOError # 輸入/輸出異常;基本上是沒法打開文件 ImportError # 沒法引入模塊或包;基本上是路徑問題或名稱錯誤 IndentationError # 語法錯誤(的子類) ;代碼沒有正確對齊 IndexError # 下標索引超出序列邊界,好比當x只有三個元素,卻試圖訪問x[5] KeyError # 試圖訪問字典裏不存在的鍵 KeyboardInterrupt # Ctrl+C被按下 NameError # 使用一個還未被賦予對象的變量 SyntaxError # Python代碼非法,代碼不能編譯(我的認爲這是語法錯誤,寫錯了) TypeError # 傳入對象類型與要求的不符合 UnboundLocalError # 試圖訪問一個還未被設置的局部變量,基本上是因爲另有一個同名的全局變量,致使你覺得正在訪問它 ValueError # 傳入一個調用者不指望的值,即便值的類型是正確的
更多異常blog
ArithmeticError AssertionError AttributeError BaseException BufferError BytesWarning DeprecationWarning EnvironmentError EOFError Exception FloatingPointError FutureWarning GeneratorExit ImportError ImportWarning IndentationError IndexError IOError KeyboardInterrupt KeyError LookupError MemoryError NameError NotImplementedError OSError OverflowError PendingDeprecationWarning ReferenceError RuntimeError RuntimeWarning StandardError StopIteration SyntaxError SyntaxWarning SystemError SystemExit TabError TypeError UnboundLocalError UnicodeDecodeError UnicodeEncodeError UnicodeError UnicodeTranslateError UnicodeWarning UserWarning ValueError Warning ZeroDivisionError
爲了保證程序的健壯性與容錯性,即在遇到錯誤時程序不會崩潰,咱們須要對異常進行處理。索引
若是錯誤發生的條件是可預知的,咱們須要用if進行處理:在錯誤發生以前進行預防。ip
AGE=10 while True: age=input('>>: ').strip() if age.isdigit(): #只有在age爲字符串形式的整數時,下列代碼纔不會出錯,該條件是可預知的 age=int(age) if age == AGE: print('you got it') break
若是錯誤發生的條件是不可預知的,則須要用到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()
一、異常類只能用來處理指定的異常狀況,若是非指定異常則沒法處理
s1 = 'hello' try: int(s1) except IndexError as e: # 未捕獲到異常,程序直接報錯 print e
二、多分支
s1 = 'hello' try: int(s1) except IndexError as e: print(e) except KeyError as e: print(e) except ValueError as e: print(e)
三、萬能異常Exception
s1 = 'hello' try: int(s1) except Exception as e: print(e)
四、也能夠在多分支後來一個Exception
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)
五、異常的其餘機構
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('不管異常與否,都會執行該模塊,一般是進行清理工做')
六、主動觸發異常
try: raise TypeError('類型錯誤') except Exception as e: print(e)
七、自定義異常
class EgonException(BaseException): def __init__(self,msg): self.msg=msg def __str__(self): return self.msg try: raise EgonException('類型錯誤') except EgonException as e: print(e)
八、斷言:assert條件
assert 1 == 1 assert 1 == 2
九、總結try...except
一、把錯誤處理和真正的工做分開來;
二、代碼更易組織,更清晰,複雜的工做任務更容易實現;
三、毫無疑問,更安全了,不至於因爲一些小的疏忽而使程序意外崩潰了。