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

我所说的“现代Python”是指在Python2.5中运行,但对于Python2.6和Python3.*的工作方式来说是“正确的”。我所说的“自定义”是指一个异常对象,它可以包含有关错误原因的额外数据:一个字符串,也可能是与异常相关的其他任意对象。

我被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中确实有特殊的含义,他们正试图贬低它,所以我想这个名字(以及这个名字)现在被禁止了?呃。

我还模糊地意识到Exception有一些神奇的参数参数,但我从未知道如何使用它;我在网上发现的许多讨论都表明,他们试图在Python 3中取消args。

更新:两个答案建议重写__init__和__str__/__unicode__/__repr_。这似乎需要很多打字,是吗?


当前回答

截至Python 3.8(2018,https://docs.python.org/dev/whatsnew/3.8.html),建议的方法仍然是:

class CustomExceptionName(Exception):
    """Exception raised when very uncommon things happen"""
    pass

请不要忘记记录,为什么需要自定义异常!

如果需要,这是处理具有更多数据的异常的方法:

class CustomExceptionName(Exception):
    """Still an exception raised when uncommon things happen"""
    def __init__(self, message, payload=None):
        self.message = message
        self.payload = payload # you could add more args
    def __str__(self):
        return str(self.message) # __str__() obviously expects a string to be returned, so make sure not to send any other data types

并像这样获取它们:

try:
    raise CustomExceptionName("Very bad mistake.", "Forgot upgrading from Python 1")
except CustomExceptionName as error:
    print(str(error)) # Very bad mistake
    print("Detail: {}".format(error.payload)) # Detail: Forgot upgrading from Python 1

有效负载=无对使其可酸洗很重要。在转储之前,必须调用error__reduce_()。加载将按预期工作。

如果需要将大量数据传输到某个外部结构,您可能应该研究如何使用pythons return语句找到解决方案。对我来说,这似乎更清晰/更像蟒蛇。高级异常在Java中大量使用,当使用框架并必须捕获所有可能的错误时,这有时会很烦人。

其他回答

截至Python 3.8(2018,https://docs.python.org/dev/whatsnew/3.8.html),建议的方法仍然是:

class CustomExceptionName(Exception):
    """Exception raised when very uncommon things happen"""
    pass

请不要忘记记录,为什么需要自定义异常!

如果需要,这是处理具有更多数据的异常的方法:

class CustomExceptionName(Exception):
    """Still an exception raised when uncommon things happen"""
    def __init__(self, message, payload=None):
        self.message = message
        self.payload = payload # you could add more args
    def __str__(self):
        return str(self.message) # __str__() obviously expects a string to be returned, so make sure not to send any other data types

并像这样获取它们:

try:
    raise CustomExceptionName("Very bad mistake.", "Forgot upgrading from Python 1")
except CustomExceptionName as error:
    print(str(error)) # Very bad mistake
    print("Detail: {}".format(error.payload)) # Detail: Forgot upgrading from Python 1

有效负载=无对使其可酸洗很重要。在转储之前,必须调用error__reduce_()。加载将按预期工作。

如果需要将大量数据传输到某个外部结构,您可能应该研究如何使用pythons return语句找到解决方案。对我来说,这似乎更清晰/更像蟒蛇。高级异常在Java中大量使用,当使用框架并必须捕获所有可能的错误时,这有时会很烦人。

要正确定义自己的异常,您应该遵循以下几个最佳实践:

定义从Exception继承的基类。这将允许轻松捕捉与项目相关的任何异常:类MyProjectError(异常):“”“MyProject异常的基类。”“”在单独的模块中组织异常类(例如exceptions.py)通常是一个好主意。要创建特定异常,请将基本异常类子类化。类CustomError(MyProjectError):“”“MyProject的自定义异常类。”“”您还可以子类化自定义异常类以创建层次结构。若要向自定义异常添加对额外参数的支持,请使用可变数量的参数定义__init__()方法。调用基类的__init__(),向其传递任何位置参数(请记住BaseException/Exception需要任意数量的位置参数)。为实例存储额外参数,例如:类CustomError(MyProjectError):定义__init__(self,*args,**kwargs):super()__init__(*参数)self.fo=kwargs.get('fo')要使用额外的参数引发此类异常,可以使用:raise CustomError(“发生了一些错误”,foo='fo')

这种设计遵循Liskov替换原则,因为您可以用派生异常类的实例替换基本异常类的一个实例。此外,它还允许您使用与父类相同的参数创建派生类的实例。

为了实现最大程度的自定义,为了定义自定义错误,您可能需要定义一个继承自Exception类的中间类,如下所示:

class BaseCustomException(Exception):
    def __init__(self, msg):
        self.msg = msg

    def __repr__(self):
        return self.msg


class MyCustomError(BaseCustomException):
    """raise my custom error"""

一个非常简单的方法:

class CustomError(Exception):
    pass

raise CustomError("Hmm, seems like this was custom coded...")

或者,在不打印__main__的情况下引发错误(可能看起来更干净整洁):

class CustomError(Exception):
    __module__ = Exception.__module__

raise CustomError("Improved CustomError!")

您应该重写__repr_或__unicode__方法,而不是使用message,构造异常时提供的参数将位于异常对象的args属性中。