
一、系統(tǒng)常見的異常
你必須先知道有那些異常,到時候遇到的時候才不會驚慌。
1.除0異常 ZeroDivisionError
出現(xiàn)情況: 1 / 0
結(jié)果: ZeroDivisionError: division by zero
2.名稱異常 NameError
出現(xiàn)情況: print(name)
結(jié)果:NameError: name 'name' is not defined
3.類型異常 TypeError
出現(xiàn)情況: print('1' + 2)
結(jié)果:TypeError: can only concatenate str (not "int") to str
4.索引異常 IndexError
出現(xiàn)情況:
l = [1, 2]
l[3]
結(jié)果:IndexError: list index out of range
5.鍵異常 KeyError
出現(xiàn)情況:
dict = {"name": "子木"}
dict["lz"]
結(jié)果:KeyError: 'lz'
6.值異常異常 ValueError
出現(xiàn)情況:
int('abc')
結(jié)果:ValueError: invalid literal for int() with base 10: 'abc'
7.屬性異常 AttributeError
出現(xiàn)情況:
class Person(object):
pass
p = Person()
print(p.name)
結(jié)果:AttributeError: 'Person' object has no attribute 'name'
8.迭代器異常 StopIteration
出現(xiàn)情況:
it = iter([1, 2])
print(next(it))
print(next(it))
print(next(it))
結(jié)果:StopIteration
總結(jié) :系統(tǒng)異常繼承樹結(jié)構(gòu) 特定異常 --> Exception -- > BaseException -- > object
二、異常處理
方案一:
try:
print("可能出現(xiàn)異常的代碼")
print(name)
except (NameError, ZeroDivisionError) as error_domin:
print('捕捉異常類型-NameError',error_domin)
except ValueError as renson:
print("捕捉異常類型-ValueError",renson)
except Exception as renson:
print("捕捉異常類型-Exception", renson)
else:
print("沒有異常執(zhí)行代碼")
finally:
print("不管有沒有異常都要執(zhí)行的代碼")
方案二:
# with 預(yù)處理A 處理完成之后執(zhí)行清理操作
# with context[as **arg]: 1、 __enter__ 方法進(jìn)入 2、執(zhí)行與具體body 3、__exit__方法退出
# with.body
import traceback
class custom_context(object):
def __enter__(self):
print("enter")
return self
# 退出時候參數(shù)都是異常信息 和 追蹤信息 如果返回true 異常不會傳出去 返回false 異常會傳出去
# 這里可以把異常寫入日志
def __exit__(self, exc_type, exc_val, exc_tb):
print(self, exc_type, exc_val, exc_tb)
print("exit")
print(traceback.extract_tb(exc_tb))
return True
# context 是 __enter__ 返回的對象
with custom_context() as context:
print("主體代碼", context)
2.手動拋出異常
def set_age(age):
if age <= 0 or age > 100:
raise ValueError("設(shè)置年齡不對") # 手動拋出異常
else:
print("設(shè)置張三的年齡是", age)
set_age(18)
set_age(-18)
3.自定義異常
class CustomException(Exception):
def __init__(self, message, error_code):
self.message = message
self.errorCode = error_code
def __str__(self):
return "自定義異常類的信息:{} 錯誤碼:{}".format(self.message, self.errorCode)
def set_age(age):
if age <= 0 or age > 100:
raise CustomException("設(shè)置年齡不對", 404)
else:
print("設(shè)置張三的年齡是", age)
try:
set_age(-18)
except Exception as e:
print(e)
最后贈言
學(xué)無止境,學(xué)習(xí)Python的伙伴可以多多交流。