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

问题:

What's the proper way to declare custom exception classes in modern Python? 在现代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

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. “现代Python”是指能够在Python 2.5中运行但对于Python 2.6和Python 3. *是“正确”的方式。 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. 所谓“自定义”,是指一个Exception对象,该对象能够包含有关错误缘由的其余数据:字符串,也许还包括与该异常相关的其余任意对象。 工具

I was tripped up by the following deprecation warning in Python 2.6.2: 我在Python 2.6.2中被如下弃用警告绊倒了: spa

>>> 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

It seems crazy that BaseException has a special meaning for attributes named message . BaseException对于名为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? 我从PEP-352收集到,该属性确实在2.5中有特殊含义,所以他们想弃用该属性,因此我猜测如今禁止使用该名称(以及一我的)。 Ugh. 啊。 .net

I'm also fuzzily aware that Exception has some magic parameter args , but I've never known how to use it. 我也模糊地知道Exception有一些魔术参数args ,可是我历来不知道如何使用它。 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. 我在网上发现的不少讨论都代表他们正在尝试消除Python 3中的args。 code

Update: two answers have suggested overriding __init__ , and __str__ / __unicode__ / __repr__ . 更新:有两个答案建议覆盖__init____str__ / __unicode__ / __repr__ That seems like a lot of typing, is it necessary? 好像要打不少笔,有必要吗? 对象


解决方案:

参考一: https://stackoom.com/question/5XI7/在现代Python中声明自定义异常的正确方法
参考二: https://oldbug.net/q/5XI7/Proper-way-to-declare-custom-exceptions-in-modern-Python