常見(jiàn)錯(cuò)誤
(1)NameError:命名錯(cuò)誤
(2)SyntaxError:語(yǔ)法錯(cuò)誤
(3)IOError:IO錯(cuò)誤
(4)ZeroDivisionError:除0錯(cuò)誤
(5)ValueError:值錯(cuò)誤
(6)KeyboardInterrupt:用戶干擾退出
try & execpt
# try -> else -> finally
try:
try_suite
except IOError, e:
do_except
except ValueError, e:
do_except
else:
do_else
finally:
do_finally
with as
with語(yǔ)句實(shí)質(zhì)上是上下文管理
理論知識(shí)
上下文管理協(xié)議:包含方法:__enter__(),__exit()__
需要注意的是,with語(yǔ)句代碼段中,如果出現(xiàn)了異常,那么將無(wú)法保證with語(yǔ)句一定能將file關(guān)閉。
try:
with open('test.txt', 'r') as f:
f.seek(-1, os.SEEKSET) # 此處會(huì)報(bào)錯(cuò),代碼意思是找到了文件頭部之后的-1的位置,顯然不存在。
except ValueError,e:
handle_except
# 當(dāng)代碼中使用了try-except后,那么with語(yǔ)句在先將文件關(guān)閉后,再將error拋出,截獲后再對(duì)error進(jìn)行處理。
應(yīng)用場(chǎng)景
1.文件操作;
2.進(jìn)程線程之間互斥對(duì)象,例如互斥鎖;
3.支持上下文的其他對(duì)象。
raise & assert
raise XXError("ErrorInfo") // python3以后的寫法
raise XXError. "ErrorInfo" // python2中的寫法,但在2中也支持上面的寫法
raise NameError('HiThere')
Traceback (most recent call last):
File "<stdin>", line 1, in
NameError: HiThere
assert語(yǔ)句
斷言語(yǔ)句:assert語(yǔ)句用于檢測(cè)表達(dá)式是否為真,如果為假,引發(fā)AssertionError錯(cuò)誤;
assert exception, "errorInfo"
標(biāo)準(zhǔn)異常 & 自定義異常
Paste_Image.png
自定義異常:
// 定義
class FileError(IOError):
pass
// 觸發(fā)異常
assert FileError, "file Error!"
try:
raise FileError, "Test FileError"
except FileError, e:
print(e)
class CustomError(Exception):
def __init__(self, info):
Exception.__init__(self) # 重寫父類方法
self.errorinfo = info
def __str__(self):
return "CustionError:%s" % self.errorinfo
try :
raise CustomError("test CustomError")
except CustomError, e:
print(e) ##