class MyException(Exception):
def __str__(self):
return self.args[0]
def DoWork():
raise MyException("My hoverboard is full of eels")
pass
if __name__ == '__main__':
try:
DoWork()
except MyException as ex:
print("This will get printed: " + str(ex)) #Line1
print("This will not get printed and will raise exception: " + ex) #Line2
Why does an exception needs an explicit conversion in line 1. Ideally it should work as shown in Line2.
Note: I have tried both – the removal of str from MyException class and addition of str; neither of them worked.
Please help.
You have to convert it to a string because
x + yends up callingx.__add__(y), so whenxis a string you callstr.__add__, which operates on two strings, not on a string and an Exception. Python’s built in operators and types generally don’t automatically try to force things to be the right type (like javascript, for example), you have to be explicit. This is no different to having to useint()inx = 1 + int("12"), for example.Note that if you don’t want to use
str(), you can use%formatting: