解决方案-几乎不需要编码
只是继承您的异常类,
Exception并将消息作为第一个参数传递给构造函数
例:
class MyException(Exception): """My documentation"""try: raise MyException('my detailed description')except MyException as my: print my # outputs 'my detailed description'您可以使用
str(my)或(不太优雅)
my.args[0]来访问自定义消息。
背景
在较新的Python版本(从2.6开始)中,我们应该从Exception继承自定义异常类,而Exception(从Python
2.5开始)从baseException继承。在PEP
352中详细描述了背景。
class baseException(object): """Superclass representing the base of the exception hierarchy. Provides an 'args' attribute that contains all arguments passed to the constructor. Suggested practice, though, is that only a single string argument be passed to the constructor."""
__str__并且
__repr__已经以有意义的方式实现,尤其是对于仅一个arg(可用作消息)的情况。
您不需要重复
__str__或
__init__实施或创建
_get_message其他人建议的内容。



