Reputation: 13
I'm learning about python. I'm doing and application to monitoring voltage and I found that sometimes when you rise and error the final information about this error is not enough to understand it, when it happens. My question is: What is the best way to give the information?
For example, I know that I can do something like that:
class IncorrectVoltageError(Exception):
pass
raise IncorrectVoltageError('Incorrect voltage, should be 5V')
>>IncorrectVoltageError: Incorrect voltage, should be 5V
but if it will be a common error in my code maybe the information could be in the class explain.
class IncorrectVoltageError(Exception):
'''Incorrect voltage, should be 5V'''
pass
raise IncorrectVoltageError(IncorrectVoltageError.__doc__)
>>IncorrectVoltageError: Incorrect voltage, should be 5V
What is the best way? And are there other ways?
Thanks
Upvotes: 1
Views: 82
Reputation: 39
The common way is to override a specific method from the parent class. In that case, it is __init__
method.
Something like this:
class IncorrectVoltageError(Exception):
def __init__(self, message=None, *args, **kwargs):
if not message:
message = "Incorrect voltage, should be 5V"
super().__init__(message, *args, **kwargs)
Upvotes: 2