解决:During handling of the above exception, another exception occurred


解决:During handling of the above exception, another exception occurred





背景

在使用之前的代码时,报错:
Traceback (most recent call last):
File “xxx”, line xx, in
re = request.get(url)
During handling of the above exception, another exception occurred



报错问题


  Traceback (most recent call last): 
    File "xxx", line xx, in  
        re =  request.get(url) 
  During handling of the above exception, another exception occurred



报错翻译

主要报错信息内容翻译如下所示:


  Traceback (most recent call last): 
    File "xxx", line xx, in  
        re =  request.get(url) 
  During handling of the above exception, another exception occurred

翻译:

追溯(最近一次调用):
文件“xxx”,第xx行,在
re=request.get(url)
在处理上述异常的过程中,发生了另一个异常



报错位置代码


...
    re =  request.get(url) 
...



报错原因

经过查阅资料,发现是这个错误通常是由于在处理异常的except分支或离开tryfinally分支有raise,就会出现这样的提示。

本例中的程序连续发起数千个请求,大量请求失败就会报这个错误:During handling of the above exception, another exception occurred

小伙伴们按下面的解决方法即可解决!!!



解决方法

要解决这个错误,需要可以使用try捕获异常但不用raise,即可解决。

正确的代码是:


...
  try:
    re =  request.get(url)
  exceptprint("time out")

...

当报错发生在except时,需要在except的代码块里增加异常的try...except...,再次进行异常处理。可以参考如下代码:


x = 1
y = 0
 
try:
    result = x / y
except ZeroDivisionError:

    print("处理第一个except")
    try:
        result = x / y
    except Exception as e:
        print("处理第二个except")
        print(repr(e))

当报错发生在finally时,需要在finally的代码块里增加异常的try...except...,再次进行异常处理。可以参考如下代码:


x = 1
y = 0
 
try:
    result = x / y
except ZeroDivisionError:

    print("处理第一个except")
    
finally:
    try:
        result = x / y
    except Exception as e:
        print("处理第二个except")
        print(repr(e))


参考内容:

https://blog.csdn.net/weixin_39514626/article/details/111839821



今天的分享就到此结束了

欢迎点赞评论关注三连

在这里插入图片描述

  • 12
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ninghes

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值