日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python常用异常处理

發(fā)布時間:2025/3/21 python 54 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python常用异常处理 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

2019獨角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>

python本身的異常處理是非常友好的

把你期望正常運行的代碼放入到try中在用except捕獲你認(rèn)為意外的錯誤再執(zhí)行相應(yīng)的處理

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

期望值是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)

超出索引范圍:

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

常用錯誤異常:

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

其他異常:

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

完整的異常處理結(jié)構(gòu)

try:# 主代碼塊pass except KeyError,e:# 異常時,執(zhí)行該塊pass else:# 主代碼塊執(zhí)行完,執(zhí)行該塊pass finally:# 無論異常與否,最終執(zhí)行該塊pass

主動拋出異常

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

自定義異常

class SelfException(Exception):def __init__(self, msg):self.message = msgdef __str__(self):return self.messagetry:raise SelfException('我的異常') except SelfException as e:print(e)

?

對于必須出現(xiàn)我期望值的處理還有一種斷言的方式,如果結(jié)果為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其實還有第二個參數(shù)assert expression [, arguments] ,第二個參數(shù)為拋出的錯誤信息

如:

assert 2==1,'2不等于1'

?

轉(zhuǎn)載于:https://my.oschina.net/u/3640109/blog/3032982

總結(jié)

以上是生活随笔為你收集整理的python常用异常处理的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。