python學習筆記(二十):異常處理
阿新 • • 發佈:2018-02-24
錯誤 fetchall nbsp 如果 info blog months api root
1 def calc(a,b): 2 res=a/b 3 return res 4 def main(): 5 money=input(‘輸入多少錢:‘) 6 months=input(‘還幾個月:‘) 7 try: 8 res=calc(int(money),int(months)) 9 except ZeroDivisionError as e:#try裏面的代碼如果出錯了,走except裏的代碼 10 print(‘還款月數不能小於1‘,e) 11 except ValueError as e:12 print(‘輸入必須是整數,%s‘%e) 13 else:#沒有出錯的情況下走else 14 print(‘每個月應該還%s‘%res) 15 main()
1 def calc(a,b): 2 res=a/b 3 return res 4 def main(): 5 money=input(‘輸入多少錢:‘) 6 months=input(‘還幾個月:‘) 7 try: 8 res=calc(int(money),int(months)) 9 except Exception as e:10 print(‘輸入錯誤,請檢查輸入!%s‘ % e)#出錯就報異常,不分具體的情況 11 main()
1 import traceback 2 def calc(a,b): 3 res=a/b 4 return res 5 def main(): 6 money=input(‘輸入多少錢‘) 7 months=input(‘還幾個月:‘) 8 try: 9 res=calc(int(money),int(months)) 10 except ZeroDivisionError as e:#try裏面的代碼如果出錯了,走except裏的代碼11 traceback.print_exc()#只是輸出報錯的詳細信息而已 12 print(‘還款月數不能小於1‘,e) 13 except ValueError as e: 14 print(‘輸入必須是整數,%s‘%e) 15 else: #沒有出錯的情況下走else 16 print(‘每個月應還%s‘%res) 17 print(‘hahahaa‘) 18 main()
1 import pymysql 2 def main2(sql): 3 try: 4 conn=pymysql.connect(host=‘122.932.122.11‘,user=‘root‘,password=‘123456‘,db=‘test‘) 5 except Exception as e: 6 print(‘數據庫連接不了,%S‘%e) 7 else: 8 cur=conn.cursor() 9 try: 10 cur.execute(sql) 11 except Exception as e: 12 print(‘sql語句有錯誤!%s是"%s‘%(e,sql)‘) 13 else: 14 res=cur.fetchall() 15 return res 16 finally:#不管有沒有捕捉到異常,都會走這裏 17 cur.close() 18 conn.close()
1 try: 2 a=int(input(‘xx:‘)) 3 b=int(input(‘sss:‘)) 4 res=a/b 5 except Exception as e: 6 print(e) 7 else: 8 print(res) 9 finally: 10 print(‘什麽時候到我這裏呢‘)
1 import requests 2 def req(): 3 r=requests.get(‘http://api.nnzhp.cn/api/user/all_stu‘,headers={‘Referer‘:‘http://api.nnzhp.cn/‘}) 4 print(r.json()) 5 print(r.json()[‘stu_info‘]) 6 if len(r.json()[‘stu_info‘])>0: 7 pass 8 else: 9 raise Exception(‘這個接口什麽數據都沒有‘)#主動拋出異常 10 req()
1 import requests 2 def req(): 3 r = requests.get(‘http://api.nnzhp.cn/api/user/all_stu‘, headers={‘Referer‘: ‘http://api.nnzhp.cn/‘}) 4 # print(r.json()) 5 # print(r.json()[‘stu_info‘]) 6 if len(r.json()[‘stu_info‘]) <0: 7 pass 8 else: 9 raise Exception(‘這個接口什麽數據都沒有‘) # 主動拋出異常 10 # raise ValueError 11 req()
python學習筆記(二十):異常處理