Python異常處理

1、什麼是異常

異常就是程序運行時發生錯誤的信號(在程序出現錯誤時,則會產生一個異常,若程序沒有處理它,則會拋出該異常,程序的運行也隨之終止),在python中,錯誤觸發的異常以下:python

一、錯誤的類型

①語法錯誤:這種錯誤,根本過不了python解釋器的語法檢測,必須在程序執行前就改正

#語法錯誤示範一
if
#語法錯誤示範二
def test:
    pass
#語法錯誤示範三
class func
    pass
#語法錯誤示範四
print(hello word
View Code

②邏輯錯誤

#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'
View Code

二、異常的種類

①經常使用異常

AttributeError 試圖訪問一個對象沒有的樹形,好比foo.x,可是foo沒有屬性x
IOError 輸入/輸出異常;基本上是沒法打開文件
ImportError 沒法引入模塊或包;基本上是路徑問題或名稱錯誤
IndentationError 語法錯誤(的子類) ;代碼沒有正確對齊
IndexError 下標索引超出序列邊界,好比當x只有三個元素,卻試圖訪問x[5]
KeyError 試圖訪問字典裏不存在的鍵
KeyboardInterrupt Ctrl+C被按下
NameError 使用一個還未被賦予對象的變量
SyntaxError Python代碼非法,代碼不能編譯(我的認爲這是語法錯誤,寫錯了)
TypeError 傳入對象類型與要求的不符合
UnboundLocalError 試圖訪問一個還未被設置的局部變量,基本上是因爲另有一個同名的全局變量,
致使你覺得正在訪問它
ValueError 傳入一個調用者不指望的值,即便值的類型是正確的
View Code

②更多異常

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
View Code

2、異常處理

一、若是錯誤發生的條件是可預知的,咱們須要用if進行處理:在錯誤發生以前進行預防

num=10
while True:
    age=input('>>: ').strip()
    if age.isdigit(): #只有在age爲字符串形式的整數時,下列代碼纔不會出錯,該條件是可預知的
        age=int(age)
        if age == num:
            print('666')
            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

三、try...except類型

①單分支:異常類只能用來處理指定的異常狀況,若是非指定異常則沒法處理

s1 = 'hello'
try:
    int(s1)
except IndexError as e: # 未捕獲到異常,程序直接報錯
    print e
View Code

②多分支:若是你對錯誤緣由須要進行不一樣分流或者程序處理

s1 = 'hello'
try:
    int(s1)
except IndexError as e:
    print(e)
except KeyError as e:
    print(e)
except ValueError as e:
    print(e
View Code

③萬能異常Exception:若是對錯誤緣由不關心,只是想不讓其報錯,那麼程序中你就用萬能處理

s1 = 'hello'
try:
    int(s1)
except Exception as e:
    print(e)
View Code

④多分支異常與萬能異常:對某些錯誤須要進行分流處理,剩下的錯誤直接跳過

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)
View Code

⑤其它異常:若是出現異常 就不會走else邏輯,不出現異常,則執行else邏輯

try:
     print('二狗 向 臉哥轉了 200元')
     name
    print('臉哥確認收到了 200元')

except NameError:
     print('name  is not defined')

else:
    print('轉帳成功')
print(666)
View Code

⑥try except else finally:不管報不報錯都執行,若是報錯,finally是在報錯以前執行的!!!

try:
    print('二狗 向 臉哥轉了 200元')
    name
    print('臉哥確認收到了 200元')

except KeyError:
    print('name  is not defined')
#
# else:
#     print('轉帳成功')
#
finally:
    print(666)
View Code

⑦主動拋出異常

try:
    raise TypeError('類型錯誤')
except Exception as e:
    print(e)
View Code

⑧自定義異常

class PhoneConnectionError(BaseException):
     pass
try:
     raise PhoneConnectionError('類型錯誤')
except PhoneConnectionError:
     print('手機鏈接出現問題')
View Code

⑨斷言:assert 條件

assert 1 == 1  
assert 1 == 2
View Code

3、何時用異常處理

一、首先try...except是附加給你的程序的一種異常處理的邏輯,與你的主要的工做是沒有關係的,這種東西加的多了,會致使你的代碼可讀性變差git

二、只有在錯誤發生的條件沒法預知的狀況下,才應該加上try...exceptide

三、有的同窗會這麼想,學完了異常處理後,好強大,我要爲個人每一段程序都加上try...except,堅定不容許……spa

相關文章
相關標籤/搜索