python 异常链开启关闭

如果try catch,捕获异常后,触发了另一个异常就会在控制台打印异常链,来表明异常的关系。

比如两个异常消息提示:

the above exception was the direct cause of the following exception 上面的异常是下面的异常的直接原因

During handling of the above exception, another exception occurred 当处理以上异常时另一个异常发生了。

例子

def fun1():
    try:
        t1 = ["1","2"]
        print(t1[3])

    except IndexError as e:
        print("fun1 e error: "+str(e))
        raise ValueError("fun1 Value error")
        # raise e

def fun2():
    try:
        fun1()
    except Exception as e:
        print("fun2 e error: " + str(e))
        # raise TypeError("Handling exception error")
        raise e

try:
    cause = None
    context = None
    support_context = None
    fun2()

except Exception as e:
    print(str(e))
    # 使用下面一层的异常 没有异常链
    # raise e
    # 另外使用一个异常,有异常链 During handling of the above exception, another exception occurred:
    # raise RuntimeError("Final exception")
    # 另外一个异常,但是from None,没有异常链
    # raise RuntimeError("Final exception") from None
finally:
    print("finally")

控制台打印

fun1 e error: list index out of range
fun2 e error: fun1 Value error
fun1 Value error
finally
Traceback (most recent call last):
  File "E:/software/code/pythonwork/pythonProject/geventDemo/test2.py", line 4, in fun1
    print(t1[3])
IndexError: list index out of range

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "E:/software/code/pythonwork/pythonProject/geventDemo/test2.py", line 23, in 
    fun2()
  File "E:/software/code/pythonwork/pythonProject/geventDemo/test2.py", line 17, in fun2
    raise e
  File "E:/software/code/pythonwork/pythonProject/geventDemo/test2.py", line 13, in fun2
    fun1()
  File "E:/software/code/pythonwork/pythonProject/geventDemo/test2.py", line 8, in fun1
    raise ValueError("fun1 Value error")
ValueError: fun1 Value error

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "E:/software/code/pythonwork/pythonProject/geventDemo/test2.py", line 30, in 
    raise RuntimeError("Final exception")
RuntimeError: Final exception

Process finished with exit code 1

有异常链能清楚的看到,所有的异常,和最开始,最后的异常。但是也会有控制台输出太长,影响其它的打印输出问题,所以可以控制是否启用控制链。

raise 语句支持可选的 from 子句,该子句用于启用链式异常。 例如:

# exc must be exception instance or None.
raise RuntimeError from exc

 就是说,如果想开启异常链,用raise anotherError from exc,关闭用raise anotherErroe from None。当处理一个异常时触发另一个异常,就会触发异常链,除非raise anotherErroe from None关闭。

具体的原理看下官方文档。

参考文档:

8. 错误和异常 — Python 3.9.17 文档

你可能感兴趣的:(python,开发语言)