python---異常處理

異常和錯誤

程序中不免出現錯誤,而錯誤分紅兩種

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

#語法錯誤示範一
if

#語法錯誤示範二
def test:
    pass

#語法錯誤示範三
print(haha

2.邏輯錯誤(邏輯錯誤)git

#用戶輸入不完整(好比輸入爲空)或者輸入非法(輸入不是數字)
num=input(">>: ")
int(num)

#沒法完成計算
res1=1/0
res2=1+'str'

什麼是異常

異常就是程序運行時發生錯誤的信號,在python中,錯誤觸發的異常以下安全

clipboard.png

python中的異常種類

在python中不一樣的異常能夠用不一樣的類型(python中統一了類與類型,類型即類)去標識,不一樣的類對象標識不一樣的異常,一個異常標識一種錯誤
1.觸發IndexErrorspa

l=['egon','aa']
l[3]

2.觸發KeyErrorcode

dic={'name':'egon'}
dic['age']

3.觸發ValueError對象

s='hello'
int(s)

4.經常使用異常索引

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

5.更多異常ip

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判斷式

1.正常的代碼內存

num1=input('>>: ') #輸入一個字符串試試
int(num1)

2.使用if判斷進行異常處理utf-8

#_*_coding:utf-8_*_

num1=input('>>: ') #輸入一個字符串試試
if num1.isdigit():
    int(num1) #咱們的正統程序放到了這裏,其他的都屬於異常處理範疇
elif num1.isspace():
    print('輸入的是空格,就執行我這裏的邏輯')
elif len(num1) == 0:
    print('輸入的是空,就執行我這裏的邏輯')
else:
    print('其餘情狀況,執行我這裏的邏輯')

'''
問題一:
使用if的方式咱們只爲第一段代碼加上了異常處理,但這些if,跟你的代碼邏輯並沒有關係,這樣你的代碼會由於可讀性差而不容易被看懂

問題二:
這只是咱們代碼中的一個小邏輯,若是相似的邏輯多,那麼每一次都須要判斷這些內容,就會倒置咱們的代碼特別冗長。
'''

總結:

1.if判斷式的異常處理只能針對某一段代碼,對於不一樣的代碼段的相同類型的錯誤你須要寫重複的if來進行處理。

2.在你的程序中頻繁的寫與程序自己無關,與異常處理有關的if,會使得你的代碼可讀性極其的差

3.if是能夠解決異常的,只是存在1,2的問題,因此,千萬不要妄下定論if不能用來異常處理。

def test():
    print('test running')
choice_dic={
    '1':test
}
while True:
    choice=input('>>: ').strip()
    if not choice or choice not in choice_dic:continue #這即是一種異常處理機制啊
    choice_dic[choice]()

python爲每一種異常定製了一個類型,而後提供了一種特定的語法結構用來進行異常處理

1.基本語法

try:
     被檢測的代碼塊
except 異常類型:
     try中一旦檢測到異常,就執行這個位置的邏輯
讀文件例1
f = open('a.txt')

g = (line.strip() for line in f)
for line in g:
    print(line)
else:
    f.close()
讀文件例2
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()

next(g)會觸發迭代f,依次next(g)就能夠讀取文件的一行行內容,不管文件a.txt有多大,同一時刻內存中只有一行內容。
提示:g是基於文件句柄f而存在的,於是只能在next(g)拋出異常StopIteration後才能夠執行f.close()

2.異常類只能用來處理指定的異常狀況,若是非指定異常則沒法處理。

s1 = 'hello'
try:
    int(s1)
except IndexError as e:
    print(e)

3.多分支

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

4.萬能異常 在python的異常中,有一個萬能異常:Exception,他能夠捕獲任意異常

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

4.1.若是你想要的效果是,不管出現什麼異常,咱們統一丟棄,或者使用同一段代碼邏輯去處理他們,那麼騷年,大膽的去作吧,只有一個Exception就足夠了。

s1 = 'hello'
try:
    int(s1)
except Exception,e:
    '丟棄或者執行其餘邏輯'
    print(e)

#若是你統一用Exception,沒錯,是能夠捕捉全部異常,但意味着你在處理全部異常時都使用同一個邏輯去處理(這裏說的邏輯即當前expect下面跟的代碼塊)

4.2若是你想要的效果是,對於不一樣的異常咱們須要定製不一樣的處理邏輯,那就須要用到多分支了

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

4.3多分支加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)

3.異常的其餘機構

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('不管異常與否,都會執行該模塊,一般是進行清理工做')

4.主動觸發異常

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

5.自定義異常

class EvaException(BaseException):
    def __init__(self,msg):
        self.msg=msg
    def __str__(self):
        return self.msg

try:
    raise EvaException('類型錯誤')
except EvaException as e:
    print(e)

6.斷言

# assert 條件
 
assert 1 == 1
 
assert 1 == 2

總結:try..except的方式比較if的方式的好處

1:把錯誤處理和真正的工做分開來
2:代碼更易組織,更清晰,複雜的工做任務更容易實現;
3:毫無疑問,更安全了,不至於因爲一些小的疏忽而使程序意外崩潰了;
相關文章
相關標籤/搜索