python經常使用異常處理

python自己的異常處理是很是友好的python

把你指望正常運行的代碼放入到try中在用except捕獲你認爲意外的錯誤再執行相應的處理express

try:
    pass
except Exception as err:
    print(err)

code

指望值是int類型:對象

s1 = 'hello'
try:
    int(s1)
except ValueError as err:
    print(err)

期待的key不存在:索引

dic = {'k1':'v1'}
try:
    dic['k20']
except KeyError as err:
    print(err)

超出索引範圍:it

dic = ["wupeiqi", 'alex']
try:
    dic[10]
except IndexError as err:
    print(err)

經常使用錯誤異常:io

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

其餘異常:class

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變量

完整的異常處理結構

try:
    # 主代碼塊
    pass
except KeyError,e:
    # 異常時,執行該塊
    pass
else:
    # 主代碼塊執行完,執行該塊
    pass
finally:
    # 不管異常與否,最終執行該塊
    pass

主動拋出異常

try:
    raise Exception('錯誤了。。。')
except Exception as err:
    print(err)

自定義異常

class SelfException(Exception):
 
    def __init__(self, msg):
        self.message = msg
 
    def __str__(self):
        return self.message
 
try:
    raise SelfException('個人異常')
except SelfException as e:
    print(e)

 

對於必須出現我指望值的處理還有一種斷言的方式,若是結果爲false則拋出錯誤

python assert語法

例:

assert 1==1
assert 2+2==2*2
assert len(['my boy',12])<10
assert range(4)==[0,1,2,3]

assert其實還有第二個參數assert expression [, arguments] ,第二個參數爲拋出的錯誤信息

如:

assert 2==1,'2不等於1'
相關文章
相關標籤/搜索