Proper way to declare custom exceptions in modern Python? -


what's proper way declare custom exception classes in modern python? primary goal follow whatever standard other exception classes have, (for instance) string include in exception printed out whatever tool caught exception.

by "modern python" mean run in python 2.5 'correct' python 2.6 , python 3.* way of doing things. , "custom" mean exception object can include data cause of error: string, maybe other arbitrary object relevant exception.

i tripped following deprecation warning in 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 of python 2.6 

it seems crazy baseexception has special meaning attributes named message. gather pep-352 attribute did have special meaning in 2.5 they're trying deprecate away, guess name (and 1 alone) forbidden? ugh.

i'm fuzzily aware exception has magic parameter args, i've never known how use it. nor sure it's right way things going forward; lot of discussion found online suggested trying away args in python 3.

update: 2 answers have suggested overriding __init__, , __str__/__unicode__/__repr__. seems lot of typing, necessary?

maybe missed question, why not:

class myexception(exception):     pass 

edit: override (or pass args), this:

class validationerror(exception):     def __init__(self, message, errors):          # call base class constructor parameters needs         super(validationerror, self).__init__(message)          # custom code...         self.errors = errors 

that way pass dict of error messages second param, , later e.errors


Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -