一、代码异常报错如下:
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