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

在现代Python中声明自定义异常的正确方法?

在现代Python中声明自定义异常的正确方法?

也许我错过了这个问题,但是为什么不呢?

class MyException(Exception):
    pass

编辑:要覆盖某些内容(或传递额外的args),请执行以下操作:

class ValidationError(Exception):
    def __init__(self, message, errors):

        # Call the base class constructor with the parameters it needs
        super(ValidationError, self).__init__(message)

        # Now for your custom code...
        self.errors = errors

这样,你可以将错误消息的字典传递给第二个参数,并在以后使用 e.errors

Python 3更新:在Python 3+中,你可以使用以下更紧凑的用法super()

class ValidationError(Exception):
    def __init__(self, message, errors):

        # Call the base class constructor with the parameters it needs
        super().__init__(message)

        # Now for your custom code...
        self.errors = errors
python 2022/1/1 18:16:43 有441人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

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

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

请先登录

推荐问题


联系我
置顶