目錄
raise 丟擲異常:
使用者自定義異常
try語句總結
斷言異常
源**:mts@desktop-mts:~/document/python$ cat try.py
import os
try:
raise oserror('os.mkdir(new)') # 人為丟擲異常
except oserror as e:
print("oops! that was no valid number:try again")
os.mkdir('new')
print("\n*******{}".format(e))
print("######")
raise
執行結果:下列**類b 表示自定義異常 繼承類exception的屬性:mts@desktop-mts:~/document/python$ python try.py
oops! that was no valid number:try again
*******os.mkdir(new) # 輸出的 e 就是 raise後 oserror中的字串
######
traceback (most recent call last):
file "try.py", line 3, in raise oserror('os.mkdir(new)')
oserror: os.mkdir(new) # 繼續丟擲異常 之後的**不做處理
mts@desktop-mts:~/document/python$ cat try2.py
class b(exception):
pass
class c(b):
pass
class d(c):
pass
for cls in [b, c, d]:
try:
raise cls()
except d:
print("d")
except c:
print("c")
except b:
print("b")
mts@desktop-mts:~/document/python$ python try2.pybc
d
class b(exception):
pass
class c(b):
pass
class d(c):
pass
for cls in [b, c, d]:
try:
raise cls()
except b:
print("b")
except c:
print("c")
except d:
print("d")
mts@desktop-mts:~/document/python$ python try2.pybb
b
class error(exception):
pass
class inputerror(error):
def __init__(self, expression, message):
self.expression = expression
self.message = message
try:
raise inputerror('###1error###','abc')
except inputerror as e:
print(e.expression)
print("$$$$$$$$$$$$")
except error:
print("b")
mts@desktop-mts:~/document/python$ python try.py
###1error###
$$$$$$$$$$$$
mts@desktop-mts:~/document/python$
自定義異常的引數 instance.argsclass error(exception):
pass
class inputerror(error):
def __init__(self, expression, message):
self.expression = expression
self.message = message
try:
raise inputerror('###1error###','abc')
except error:
print("b")
except inputerror as e:
print(e.expression)
print("$$$$$$$$$$$$")
mts@desktop-mts:~/document/python$ python try.py
b
>>> class error(exception):
... pass
...>>> try:
... raise error('abc','def','gh')
... except error as e:
... print(e.args)
...('abc', 'def', 'gh')
>>>
try:
aexcept errorname:
belse:
cfinally:
d執行a的話必然執行c和d
執行b的話必然執行d
不管怎樣用必然執行d
assert 1==2,12
等價於
if not 1==2:
raise assertionerror('12')
--------例如一下**---------------------
>>> assert 1==2, 12
traceback (most recent call last):
file "", line 1, in assertionerror: 12
>>> if not 1==2:
... raise assertionerror(12)
...traceback (most recent call last):
file "", line 2, in assertionerror: 12
python語法31 異常處理
一 基本的異常處理 deftesttryexception try f open myfile.txt s f.readline f.close i int s.strip except ioerror as ioerror print ioerror except valueerror as va...
python異常處理 Python 異常處理
使用者輸入不完整 比如輸入為空 或者輸入非法 輸入不是數字 異常就是程式執行時發生錯誤的訊號,在python中,錯誤觸發的異常如下 在python中不同的異常可以用不同的型別 python中統一了類與型別,型別即類 去標識,不同的類物件標識不同的異常,乙個異常標識一種錯 觸發indexerror 觸...
異常處理基本語法
異常發生第一現場,丟擲異常 void function 在需要關注異常的地方,捕捉異常 trycatch 異常型別宣告 catch 異常型別 形參 catch 注意事項 通過throw操作建立乙個異常物件並拋擲 在需要捕捉異常的地方,將可能丟擲異常的程式段嵌在try塊之中 按正常的程式順序執行到達t...