只是继承您的异常类,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(可用作消息)的情况。