zoukankan      html  css  js  c++  java
  • python自动化测试-D9-学习笔记之二(异常处理)

    '''
    异常处理
    '''

    import traceback
    def calc(a,b):
    res = a/b
    return res
    # print(calc(10,1))
    # print(calc(10,0)) # 除数为0 的时候报错了,所以需要进行异常处理
    def main():
    money = input('输入多少钱:')
    months = input('需要还几个月:')
    try:# 异常处理
    res = calc(int(money),int(months))
    except ZeroDivisionError as e: # except捕捉异常,try里面的代码出错了,才会走except
    traceback.print_exc() # 只是打印 报错详细信息,程序还会继续往下走,需要import traceback
    print('还款的月数不能小于1',e)
    except ValueError as e:
    print('输入必须是整数',e)
    except Exception as e:# 捕捉任何异常
    print('未知错误!',e)
    else: # try 里面的代码没有报错,执行下面的代码
    print('每个月应还%s'%res)
    # main()

    import pymysql
    def main2(sql):
    try:
    conn = pymysql.connect(host='211.149.218.16',
    user='jxz',
    password='123456',
    db ='jxz',
    port = 3306,
    charset = 'utf8'
    )
    except Exception as e:
    print('数据库连接不了,%s'%e)
    else:
    cur = conn.cursor()
    try:
    cur.execute(sql)
    except Exception as e:
    print('sql语句有错误,%s,sql语句是%s'%(e,sql))
    else:
    res = cur.fetchall()
    return res
    finally:# 不管有没有捕捉到异常,都会执行finally
    cur.close()
    conn.close()

    # finally 例子
    # try:
    # a=int(input('输入a:'))
    # b=int(input('输入b:'))
    # res=a/b
    # except Exception as e:
    # print(e)
    # else:
    # print(res)
    # finally:
    # print('什么时候走到我这里')
    # '''
    # 打印结果:第一种:
    # 输入a:1,输入b:2 0.5 什么时候走到我这里
    # 第二种:
    # 输入a:1,输入b:0 division by zero 什么时候走到我这里
    # '''

    #主动抛出异常
    import requests
    def req():
    r= requests.get('http://api.nnzhp.cn/api/user/all_stu',headers={'Referer':'http://api.nnzhp.cn/'})
    # print(r.json()['stu_info'])
    if len(r.json()['stu_info']) < 0:
    pass
    else:
    raise Exception('这个接口什么数据都没有') # raise 是主动抛出异常 用Exception 是自己定义的异常
    raise ValueError # 主动抛出异常 ,前提是自己知道这个异常是什么类型的异常
    req()
  • 相关阅读:
    Django render与redirect的区别
    前段(一)html基础标签
    mysql数据库多表查询及函数运算符(二)
    前段(四) JS部分
    Cookie、Session、Token、JWT总结
    前段(三)css完整部分
    django杂项 (二)
    Python框架Tornado基础(一)
    Django基础(一)
    博客园美化css/JS代码
  • 原文地址:https://www.cnblogs.com/blackbird0423/p/8543347.html
Copyright © 2011-2022 走看看