Python异常链接

Python异常链接,第1张

Python异常链接

异常链接仅在Python 3中可用,您可以在其中编写

try:    v = {}['a']except KeyError as e:    raise ValueError('failed') from e

产生像

Traceback (most recent call last):  File "t.py", line 2, in <module>    v = {}['a']KeyError: 'a'The above exception was the direct cause of the following exception:Traceback (most recent call last):  File "t.py", line 4, in <module>    raise ValueError('failed') from evalueError: failed

在大多数情况下,您甚至都不需要

from
; 默认情况下,Python 3将显示异常处理期间发生的所有异常,如下所示:

Traceback (most recent call last):  File "t.py", line 2, in <module>    v = {}['a']KeyError: 'a'During handling of the above exception, another exception occurred:Traceback (most recent call last):  File "t.py", line 4, in <module>    raise ValueError('failed')ValueError: failed

您可以在 Python 2中执行的 *** 作 是向您的异常类添加自定义属性,例如:

class MyError(Exception):    def __init__(self, message, cause):        super(MyError, self).__init__(message + u', caused by ' + repr(cause))        self.cause = causetry:    v = {}['a']except KeyError as e:    raise MyError('failed', e)


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5616508.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-15
下一篇2022-12-15

发表评论

登录后才能评论

评论列表(0条)

    保存