在现代Python中声明自定义异常的正确方法? [英] Proper way to declare custom exceptions in modern Python?

查看:184
本文介绍了在现代Python中声明自定义异常的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在现代Python中声明自定义异常类的正确方法是什么?我的主要目标是遵循其他异常类具有的任何标准,以便(例如)我捕获到异常中的任何额外字符串都可以通过捕获异常的任何工具打印出来。

What's the proper way to declare custom exception classes in modern Python? My primary goal is to follow whatever standard other exception classes have, so that (for instance) any extra string I include in the exception is printed out by whatever tool caught the exception.

现代Python是指可以在Python 2.5中运行但对于Python 2.6和Python 3. *是正确的方式。 自定义是指一个Exception对象,该对象可以包含有关错误原因的额外数据:字符串,也许还包括与异常相关的其他任意对象。

By "modern Python" I mean something that will run in Python 2.5 but be 'correct' for the Python 2.6 and Python 3.* way of doing things. And by "custom" I mean an Exception object that can include extra data about the cause of the error: a string, maybe also some other arbitrary object relevant to the exception.

我被Python 2.6.2中的以下弃用警告绊倒了:

I was tripped up by the following deprecation warning in Python 2.6.2:

>>> class MyError(Exception):
...     def __init__(self, message):
...         self.message = message
... 
>>> MyError("foo")
_sandbox.py:3: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6

BaseException 对于名为 message 的属性具有特殊含义似乎很疯狂。我从 PEP-352 收集到,该属性在2.5中确实具有特殊含义正在尝试弃用,所以我想现在禁止使用该名称(和一个人)吗? gh。

It seems crazy that BaseException has a special meaning for attributes named message. I gather from PEP-352 that attribute did have a special meaning in 2.5 they're trying to deprecate away, so I guess that name (and that one alone) is now forbidden? Ugh.

我也模糊地意识到 Exception 具有一些魔术参数 args ,但我从未知道如何使用它。我也不确定这是前进的正确方法;我在网上发现的很多讨论都表明他们正在尝试消除Python 3中的args。

I'm also fuzzily aware that Exception has some magic parameter args, but I've never known how to use it. Nor am I sure it's the right way to do things going forward; a lot of the discussion I found online suggested they were trying to do away with args in Python 3.

更新:两个答案都建议覆盖 __ init__ __ str __ / __ unicode __ / __ repr __

Update: two answers have suggested overriding __init__, and __str__/__unicode__/__repr__. That seems like a lot of typing, is it necessary?

推荐答案

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

Maybe I missed the question, but why not:

class MyException(Exception):
    pass

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

to override something (or pass extra args), do this:

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

That way you could pass dict of error messages to the second param, and get to it later with e.errors

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

Python 3 Update: In Python 3+, you can use this slightly more compact use of 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中声明自定义异常的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆