• 技术文章 >Python技术 >Python基础教程

    python异常链是什么

    小妮浅浅小妮浅浅2021-07-29 09:25:11原创2590

    说明

    1、当通过except捕捉到一个异常A后,可以用raise语句再次抛出一个异常B。

    然后我们看到的异常信息是B的信息。但我们不知道这个异常B来自哪里,此时,我们可以使用异常链。

    2、在抛出异常链时,使用raisefrom语句。

    实例

    >>> def func():
    ...     raise IOError
    ...
    >>> try:
    ...     func()
    ... except IOError as exc:
    ...     raise RuntimeError('Failed to open database') from exc
    ...
    Traceback (most recent call last):
      File "<stdin>", line 2, in <module>
      File "<stdin>", line 2, in func
    OSError
     
    The above exception was the direct cause of the following exception:
     
    Traceback (most recent call last):
      File "<stdin>", line 4, in <module>
    RuntimeError: Failed to open database

    以上就是python异常链的介绍,希望对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python异常链
    品易云
    上一篇:python raise语句重新抛出异常 下一篇:python finally语句如何使用

    相关文章推荐

    • 浅谈Python异常处理机制• Python异常处理知识点汇总,五分钟就能学会• 关于Python异常处理中try与except用法详解• python异常捕捉对字符串进行判断• python异常处理的流程是什么?• python异常参数是什么• python异常处理的两种技巧• python异常处理关键字

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网