【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()
原文地址:https://www.cnblogs.com/amengmeng/p/8522897.html