I know I can specify an arbitrary number of arguments to an Exception (or any subclass thereof) when I raise it, but I see that Exceptions have a message attribute which isn't populated.
def throw():
raise Exception("This is my message", 10)
try:
throw()
except Exception as E:
print "message = ", E.message
print E.args
produces
message =
("This is my message", 10)
What I would like to do is raise a variety ValueErrors depending on how or why a value in my function isn't valid. I would also like to attach a code, so something like
raise ValueError(1, "You need to supply a string value")
# or
raise ValueError(2, "Not a valid place name") #but it is a valid string
I'm writing a code that runs callbacks supplied by the user, and I expect the user's functions to raise ValueErrors in certain situations, but their callback can also call into some library functions I provide, and I want to be able distinguish between the user's ValueErrors and Mine.
I know I can subclass the ValueError and check for that exception type explicitly, but that seems like overkill. These are all errors with user supplied values after all, so I would like to use the first argument to the exception as a code, and then somehow set the message attribute explicitly
raise ValueError(10, message = "Error 10 is something quite specific")
The above doesn't work, because exceptions don't accept keyword arguments on init.
The message attribute is set when the Exception
instance is created with a single argument. Otherwise it is empty:
In [1]: Exception(42).message
Out[1]: 42
In [2]: Exception('foo').message
Out[2]: 'foo'
In [3]: Exception('foo', 42).message
Out[3]: ''
Of course you can create an instance of Exception
and manually set its .message
attribute before raising:
e = Exception()
e.message = 'test'
raise e
But it would probably make a lot of sense to use a custom exception class instead.
Also note that Exception
does not have a message
attribute in Python 3, only args
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments