您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python异常链接

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 e
ValueError: 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

您可以在 是向您的异常类添加自定义属性,例如:

class MyError(Exception):
    def __init__(self, message, cause):
        super(MyError, self).__init__(message + u', caused by ' + repr(cause))
        self.cause = cause

try:
    v = {}['a']
except KeyError as e:
    raise MyError('Failed', e)
python 2022/1/1 18:33:07 有203人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶