一苫纤、 基本格式
# 示例一:importrequeststry:# 嘗試進(jìn)行下面操作玻孟,如果可以執(zhí)行,就執(zhí)行下面代碼ret = requests.get('http://www.google.com')? ? print(ret.text)exceptExceptionase:# 如果不可以執(zhí)行(平時(shí)會(huì)報(bào)錯(cuò))樟凄,這時(shí)不會(huì)報(bào)錯(cuò)烧给,執(zhí)行下面代碼print('請(qǐng)求異常')# 示例二:try:? ? v = []? ? v[11111]# IndexError類型的異常exceptValueErrorase:# ValueError是一個(gè)類,繼承Exception侵浸,只能捕獲到ValueError類型的異常passexceptIndexErrorase:# IndexError是一個(gè)類旺韭,繼承Exception政供,只能捕獲到IndexError類型的異常passexceptExceptionase:# Exception是一個(gè)類厂庇,可以捕獲到所有異常print(e)# e是Exception類的對(duì)象,存儲(chǔ)了一個(gè)錯(cuò)誤信息
finally
try:? ? int('asdf')exceptExceptionase:? ? print(e)finally:? ? print('最后無論對(duì)錯(cuò)都會(huì)執(zhí)行')# 特殊情況:deffunc():try:? ? ? ? int('asdf')exceptExceptionase:return123finally:? ? ? ? print('最后')# 無論對(duì)錯(cuò)伯诬,函數(shù)中遇到return澳腹,也會(huì)執(zhí)行织盼,執(zhí)行完后再returnfunc()
建議:書寫函數(shù)或功能時(shí),建議用try包裹一下酱塔,避免報(bào)錯(cuò)
示例
# 1. 寫函數(shù)沥邻,函數(shù)接受一個(gè)列表,請(qǐng)將列表中的元素每個(gè)都 +100deffunc(arg):result = []foriteminarg:ifitem.isdecimal():? ? ? ? ? ? result.append(int(item) +100)returnresult# 2. 寫函數(shù)去羊娃,接受一個(gè)列表唐全。列表中都是url,請(qǐng)?jiān)L問每個(gè)地址并獲取結(jié)果importrequestsdeffunc1(url_list):result = []try:forurlinurl_list:? ? ? ? ? ? response = requests.get(url)? ? ? ? ? ? result.append(response.text)exceptExceptionase:passreturnresultdeffunc2(url_list):result = []forurlinurl_list:try:? ? ? ? ? ? response = requests.get(url)? ? ? ? ? ? result.append(response.text)exceptExceptionase:passreturnresult# 這兩個(gè)函數(shù)執(zhí)行結(jié)果是不一樣的蕊玷,是try所處的位置不同導(dǎo)致的func1(['http://www.baidu.com','http://www.google.com','http://www.bing.com'])func2(['http://www.baidu.com','http://www.google.com','http://www.bing.com'])
二邮利、 主動(dòng)觸發(fā)異常
try:? ? int('123')raiseException('XXX')# 代碼中主動(dòng)拋出異常exceptExceptionase:? ? print(e)# XXX
示例:
deffunc():result =Truetry:withopen('x.log',mode='r',encoding='utf-8')asf:? ? ? ? ? ? data = f.read()if'alex'notindata:raiseException()exceptExceptionase:? ? ? ? result =Falsereturnresult
三、 自定義異常
classMyException(Exception):# 自定義異常垃帅,繼承Exceptionpasstry:raiseMyException('asdf')# 主動(dòng)觸發(fā)自定義異常延届,只有自定義異常自己和Exception能捕獲到exceptMyExceptionase:? ? print(e)
勤勤懇懇更博,點(diǎn)點(diǎn)滴滴記錄贸诚; 格式小問題方庭,望諒解; 有錯(cuò)誤酱固,歡迎指點(diǎn)二鳄!異常處理