python之异常处理

Posted 青青子佩-学海无涯,回头是岸

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python之异常处理相关的知识,希望对你有一定的参考价值。

先来看一段代码:

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之异常处理的主要内容,如果未能解决你的问题,请参考以下文章

python进阶之异常处理

Python 之 程序异常处理

Python之错误与异常处理

what's the python之异常处理

python基础之异常处理

Python之面向对象异常处理