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 <module>
    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 <module>
    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 文档

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值