【Python】學習筆記7-異常處理try。。except .. as e ....else
1、捕捉異常需要進入trackback包
import traceback
def clac(a,b):
return a/b
2、單獨捕捉異常try ....except...else ,捕捉所有異常Exception
def main():
money = input("輸入多少錢:")
months = input("還幾個月:")
try:
res = clac(int(money),int(months))
except ZeroDivisionError as e:
print('還款的月數不能小于1,',e)
# traceback.print_exc() #可以輸出報錯的詳細信息,哪行錯誤
except ValueError as e: #ValueError可以先運行一次后,在錯誤結果中獲取
print('輸入必須是整數%s',e)
# except Exception as e: #捕捉到所有異常,當不確定是哪種異常時,可以使用
# print('未知錯誤!',e)
else:#沒有錯的情況下走else
print('每月應該還%s' % res)
main()
3、finally#不管有沒有捕捉到異常,都會走到這里
import pymysql
def main2(sql):
try :
conn = pymysql.connect(host = '122.33.22.33',user = 'root',password = '123456',port = '3306')
except Exception as e:
print('shujukulianjiebuliao,%s'%e)
else:
cur = conn.cursor()
try:
cur.execute(sql)
except Exception as e:
print('sql error:%s,sql = %s'%(e,sql))
else:
res = cur.fetchall()
return res
finally: #不管有沒有捕捉到異常,都會走到這里
cur.close()
conn.close()
4、raise 主動拋出異常,raise關鍵字后面是拋出是一個通用的異常類型
import requests
def req():
r = requests.get('http://api.nnzhp.cn/api/user/all_stu',headers={"Referer":"http://api.nnzhp.cn/"})
if len(r.json()['stu_info'])<0:
pass
else:
raise Exception('接口無返回數據') #主動拋出異常
req()

浙公網安備 33010602011771號