也许我错过了这个问题,但是为什么不呢?
class MyException(Exception):
pass
编辑:要覆盖某些内容(或传递额外的args
),请执行以下操作:
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
Python 3更新:在Python 3+中,你可以使用以下更紧凑的用法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