Reputation: 55
If I've defined a class that takes in two or more parameters:
class SomeObject:
def __init__(self, int_param, str_param):
#if parameters are wrong type:
raise TypeError("wrong type")
...
if (__name__ == "__main__"):
try:
invalid_obj = SomeObject('two', 'string')
print (invalid_obj)
except TypeError as e:
print (e)
it'll print "wrong type", but is there a way for it to also return which argument is raising the exception? Can I get the output to be:
"wrong type 'two'"
? I've tried print (e.args), print (repr(e)), and simply print(e) but the invalid argument never gets printed. Just wondering if this is possible, thank you.
edit: It works with a custom exception type, and if I list each parameter being tested individually - I also have ValueError catching for both the int_param and str_param as well, so I wanted to see if I can condense the if statements to just:
#if params not right type:
raise TypeError
#if params contain invalid value:
raise ValueError
and still get it to return the specific invalid argument that's causing the error. I'll definitely keep the custom Exception type in mind for future assignments; unfortunately for this one the instructor has "raise TypeError" and "raise ValueError" as requirements for full marks. She doesn't require the invalid argument to be returned though, that was just me being curious if I could manage it. I ended up with:
#if int_param not int:
raise TypeError("int_param {0} given is invalid type".format(int_param))
#if str_param not int:
raise TypeError("str_param {0} given is invalid type".format(str_param))
#if int_param is an invalid value:
raise ValueError("int_param {0} given is invalid value".format(int_param))
....
and so on. If anyone can see a cleaner way to do this (without a custom Exception type), please let me know!
Upvotes: 1
Views: 614
Reputation: 385
Maybe you should look for the traceback
module.
instead of raise TypeError("wrong type")
wrap traceback.print_exc()
in try, except
and see if that's what you looking for.
Upvotes: 0
Reputation: 33335
class SomeObject:
def __init__(self, int_param, str_param):
if type(int_param) != int:
raise TypeError("int_param: wrong type")
if type(str_param) != str:
raise TypeError("str_param: wrong type")
Upvotes: 2
Reputation: 229461
You can make your own exception:
class SomeObjectException(TypeError):
def __init__(self, msg, which):
TypeError.__init__(self, msg)
self.which = which
Then:
class SomeObject:
def __init__(self, int_param, str_param):
#if parameters are wrong type:
raise SomeObjectException("wrong type", int_param)
And:
if (__name__ == "__main__"):
try:
invalid_obj = SomeObject('two', 'string')
print (invalid_obj)
except SomeObjectException as e:
print (e, e.which)
Also see proper way to declare custom exceptions in modern Python.
Upvotes: 3