【转】python错误During handling of the above exception, another exception occurred是如何发生的?

文章目录

          • 原文链接https://www.pynote.net/archives/1856
          • 简单来说(try抛出连续发生错误的地方)
          • 原文内容

原文链接https://www.pynote.net/archives/1856
简单来说(try抛出连续发生错误的地方)

例如:request向数千个url发起请求时,大量url访问失败就会报During handling of the above exception, another exception occurred错误。使用try抛出异常可解决。

try:
    re =  request.get(url)
 exceptprint("time out")
原文内容

调试python代码,常常看到这样的提示,During handling of the above exception, another exception occurred。这是如何发生的?
请看如下代码:

x = 2
y = 0

try:
    result = x / y
except ZeroDivisionError:
    raise ValueError('raise in exception clause')
    print("=== division by zero!")
else:
    print("result is", result)
finally:
    raise ValueError('raise in finally clause')
    print("executing finally clause")

ZeroDivisionError必然发生,然后代码进入except分支,在这个分支中,遇到了一个raise,后面的print得不到执行。由于有finally分支,在raise之前,需要执行finally分支的代码,不幸的是,此时又遇到了raise,它后面的print也得不到执行。因此运行这段代码的效果,就是如下:

E:\py>python try.py
Traceback (most recent call last):
  File "try.py", line 8, in 
    result = x / y
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "try.py", line 10, in 
    raise ValueError('raise in exception clause')
ValueError: raise in exception clause

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "try.py", line 15, in 
    raise ValueError('raise in finally clause')
ValueError: raise in finally clause

这就是During handling of the above exception, another exception occurred的由来!在处理异常的except分支或离开try的finally分支有raise,就会出现这样的提示。
到此,自然而然我们会想到另一个问题,在这种情况下,如果这段代码整体有try护着,抛出来的异常时哪个呢?请看下面的测试代码:

def testA():
    x = 2
    y = 0
    
    try:
        result = x / y
    except ZeroDivisionError:
        raise ValueError('raise in exception clause')
        print("=== division by zero!")
    else:
        print("result is", result)
    finally:
        raise ValueError('raise in finally clause')
        print("executing finally clause")
        

try:
    testA()
except Exception as e:
    print(repr(e))

运行结果:

E:\py>python try.py
ValueError('raise in finally clause')

你可能感兴趣的:(【转】python错误During handling of the above exception, another exception occurred是如何发生的?)