Day7 - Python异常处理及traceback模块

一、代码异常报错如下:

1.列表中不存在数据报错
l = [1,2,3]
d={}
# print(d["k"])
print(l[3])

[result~]:

D:\Python\Python37\python.exe F:/飞马座_Python/Mycode/day7/异常处理.py
Traceback (most recent call last):
  File "F:/飞马座_Python/Mycode/day7/异常处理.py", line 6, in <module>
    print(l[3])
IndexError: list index out of range

Process finished with exit code 1
2.字典中不存在的key
l = [1,2,3]
d={}
print(d["k"])

[result~]:

D:\Python\Python37\python.exe F:/飞马座_Python/Mycode/day7/异常处理.py
Traceback (most recent call last):
  File "F:/飞马座_Python/Mycode/day7/异常处理.py", line 5, in <module>
    print(d["k"])
KeyError: 'k'

Process finished with exit code 1
3.处理key不存在的异常
d={}
try:
    name = d["name"]
except KeyError as e:
    print(e)
    print("出现异常了")
else:
    print("没有出现异常")

[result~]:

'name'
出现异常了
4.处理两种报错
l = [1,2,3]
d={"name":"11"}
try:
    name = d["name"]
    l[4]
except KeyError as e:
    print(e)
    print("出现异常了")
except IndexError as e:
    print(e)
    print("出现下标不存在异常")
else:
    print("没有出现异常")
5.使用Exception处理全部报错
#使用Exception处理全部报错
l = [1,2,3]
d={"name":"11"}
try:
    name = d["name"]
    l[4]
except Exception as e:
    print(e)
    print("出异常了")
else:
    print("没有出现异常")
6.tracebook模块及finally作用
#使用Exception处理全部报错
l = [1,2,3]
d={"name":"11"}
try:
    name = d["name"]
    l[4]
except Exception as e:
    #打印错误信息,但不会导致程序终止
    traceback.print_exc()
    #保存错误信息为字符串
    msg=traceback.format_exc()
    print(msg)
    print(e)
    print("出异常了")
#else非必须写
else:
    print("没有出现异常")
#finally非必须写,但出不出异常都会走
finally:
    print("出不出异常都会走")

[result~]:

D:\Python\Python37\python.exe F:/飞马座_Python/Mycode/day7/异常处理.py
Traceback (most recent call last):
  File "F:/飞马座_Python/Mycode/day7/异常处理.py", line 23, in <module>
    l[4]
IndexError: list index out of range

list index out of range
出异常了
出不出异常都会走
Traceback (most recent call last):
  File "F:/飞马座_Python/Mycode/day7/异常处理.py", line 23, in <module>
    l[4]
IndexError: list index out of range

Process finished with exit code 0
例:获取好友分组信息,并将每个分组保存在一个sheet中
import requests,xlwt
import random
url = "https://qun.qq.com/cgi-bin/qun_mgr/get_friend_list"

data = {"bkn":xxxxxxxxxxxxxxxxx}
header = {"cookie":"xxxxxxxxxxxxxxxxxxxx"}

req = requests.post(url,data,headers=header)
result = req.json().get("result")

book = xlwt.Workbook()


for index,g_info in result.items():
    g_mems = g_info.get("mems") #list
    g_name = g_info.get("gname") if g_info.get("gname") else "默认分组"
    print("当前取的分组是===================",g_name)
    try:
        sheet = book.add_sheet(g_name)
    except Exception as e:
        sheet_name = "好友分组_%s" % random.randint(1,1000)
        print("sheet页名字不合法,重新命名 : %s" % sheet_name)
        sheet = book.add_sheet(sheet_name)
    for col,mem in enumerate(g_mems):
        nick = mem.get("name")
        qq = mem.get("uin")
        sheet.write(col,0,nick)
        sheet.write(col,1,qq)
        # print("%s => %s" % (nick,qq))

book.save("qq.xls")
例2:用异常处理判断是否为合法小数
def is_float(s):
    try:
        float(s)
    except:
        return False
    return True
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值