python之異常處理

來源:互聯網
上載者:User

標籤:pymysql   關閉   sql   修改   ima   ==   執行   info   img   

先來看一段代碼:

def calc(a,b):
res = a/b
return res

def main():
money = input(‘輸入多少錢:‘)
month = input(‘還幾個月:‘)
res = calc(int(money), int(month))
return res

main()

啟動並執行時候money輸入10,month輸入0,查看結果:

啟動並執行時候money輸入aa,month輸入hhh,查看結果:hhh

 

在運行過程中我們需要對異常進行處理,讓代碼能繼續執行之後的部分,修改代碼:

def main():
money = input(‘輸入多少錢:‘)
month = input(‘還幾個月:‘)
try:
res = calc(int(money),int(month))
except ZeroDivisionError as e: #try裡面的代碼出錯,走except
print(‘還款的月數不能是0‘, e)
print(‘每個月應該還%s‘ % res)

啟動並執行,money輸入10,month輸入0,查看結果:

仍然出錯的原因是因為try裡面的代碼出錯,走except,res根本沒有值,所以我們再次修改代碼:

def main():
money = input(‘輸入多少錢:‘)
month = input(‘還幾個月:‘)
try:
res = calc(int(money),int(month))
except ZeroDivisionError as e: #try裡面的代碼出錯,走except
print(‘還款的月數不能是0‘, e)
else:
print(‘每個月應該還%s‘ % res)

 當我們輸入字母時依然報錯,我們可以繼續修改代碼:

def main():
money = input(‘輸入多少錢:‘)
month = input(‘還幾個月:‘)
try:
res = calc(int(money),int(month))
except ZeroDivisionError as e: #try裡面的代碼出錯,走except
print(‘還款的月數不能小於1‘,e)
except ValueError as e: #繼續捕獲其他異常
print(‘輸入的必須是整數。%s‘%e)
else:
print(‘每個月應該還%s‘%res)

 代碼可能還存在很多未知異常,而我們無法預知,為了使得代碼執行中不會因為報錯而終止運行,我們可以修改代碼捕獲全部異常:

def main():
money = input(‘輸入多少錢:‘)
month = input(‘還幾個月:‘)
try:
res = calc(int(money),int(month))
except ZeroDivisionError as e: #try裡面的代碼出錯,走except
print(‘還款的月數不能小於1‘,e)
except ValueError as e: #繼續捕獲其他異常
print(‘輸入的必須是整數。%s‘%e)
except Exception as e: #捕捉全部異常
print(‘捕捉全部的異常%s‘%e)
else:
print(‘每個月應該還%s‘%res)

 當我們使用try時同樣也可以捕獲完整的報錯資訊,需要引入一個新的模組traceback,修改代碼:

import traceback
def main():
money = input(‘輸入多少錢:‘)
month = input(‘還幾個月:‘)
try:
res = calc(int(money),int(month))
except ZeroDivisionError as e: #try裡面的代碼出錯,走except
traceback.print_exc() #只是輸出報錯的詳細資料,不影響代碼運行
print(‘還款的月數不能小於1‘,e)
except ValueError as e: #繼續捕獲其他異常
print(‘輸入的必須是整數。%s‘%e)
except Exception as e: #捕捉全部異常
print(‘捕捉全部的異常%s‘%e)
else:
print(‘每個月應該還%s‘%res)

執行結果:

==================================我是分割線==================================================

import pymysql
def main2():
try:
conn = pymysql.connect(host=‘122.932.122.11‘, user=‘root‘, password=‘123456‘, db=‘test‘)
except Exception as e:
print(‘資料庫連接不了,%s‘ %e)
else:
cur = conn.cursor()
except Exception as e:
print(‘sql語句有錯誤!%s。sql是"%s‘ % (e, sql))
else:
res = cur.fetchall()
return res
#except和else不會同時走到,只能走其中的一樣,所以需要把關閉遊標和串連放在兩個分支
finally: #不管有沒有捕捉到異常,都會走到這裡
cur.close()
conn.close()

 ==================================我是分割線==================================================

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()

python之異常處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.