異常就是程序運行時發生錯誤的信號(在程序出現錯誤時,則會產生一個異常,若程序沒有處理它,則會拋出該異常,程序的運行也隨之終止),在python中,錯誤觸發的異常以下:python
#語法錯誤示範一 if #語法錯誤示範二 def test: pass #語法錯誤示範三 class func pass #語法錯誤示範四 print(hello word
#TypeError:int類型不可迭代 for i in 3: pass #ValueError num=input(">>: ") #輸入hello int(num) #NameError aaa #IndexError l=['aa','bb'] l[3] #KeyError dic={'name':'alex'} dic['age'] #AttributeError class Foo:pass Foo.x #ZeroDivisionError:沒法完成計算 res1=1/0 res2=1+'str'
AttributeError 試圖訪問一個對象沒有的樹形,好比foo.x,可是foo沒有屬性x IOError 輸入/輸出異常;基本上是沒法打開文件 ImportError 沒法引入模塊或包;基本上是路徑問題或名稱錯誤 IndentationError 語法錯誤(的子類) ;代碼沒有正確對齊 IndexError 下標索引超出序列邊界,好比當x只有三個元素,卻試圖訪問x[5] KeyError 試圖訪問字典裏不存在的鍵 KeyboardInterrupt Ctrl+C被按下 NameError 使用一個還未被賦予對象的變量 SyntaxError Python代碼非法,代碼不能編譯(我的認爲這是語法錯誤,寫錯了) TypeError 傳入對象類型與要求的不符合 UnboundLocalError 試圖訪問一個還未被設置的局部變量,基本上是因爲另有一個同名的全局變量, 致使你覺得正在訪問它 ValueError 傳入一個調用者不指望的值,即便值的類型是正確的
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
ZeroDivisionErro
num=10 while True: age=input('>>: ').strip() if age.isdigit(): #只有在age爲字符串形式的整數時,下列代碼纔不會出錯,該條件是可預知的 age=int(age) if age == num: print('666') break
#基本語法爲 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
s1 = 'hello' try: int(s1) 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)
try: print('二狗 向 臉哥轉了 200元') name print('臉哥確認收到了 200元') except NameError: print('name is not defined') else: print('轉帳成功') print(666)
try: print('二狗 向 臉哥轉了 200元') name print('臉哥確認收到了 200元') except KeyError: print('name is not defined') # # else: # print('轉帳成功') # finally: print(666)
try: raise TypeError('類型錯誤') except Exception as e: print(e)
class PhoneConnectionError(BaseException): pass try: raise PhoneConnectionError('類型錯誤') except PhoneConnectionError: print('手機鏈接出現問題')
assert 1 == 1 assert 1 == 2
一、首先try...except是附加給你的程序的一種異常處理的邏輯,與你的主要的工做是沒有關係的,這種東西加的多了,會致使你的代碼可讀性變差git
二、只有在錯誤發生的條件沒法預知的狀況下,才應該加上try...exceptide
三、有的同窗會這麼想,學完了異常處理後,好強大,我要爲個人每一段程序都加上try...except,堅定不容許……spa