I am trying to write a class to display the width of square which will handle the exception of being passed a negative number.
class Square:
def __init__(self,width):
try:
self.width = width
except ValueError:
print("Width cannot be less than zero.")
def __repr__(self):
return 'Square({0})'.format(self.width)
def __str__(self):
return "Square(" + str(self.width) + ")"
At the moment this code will give the correct output for positive input, but the exception is not being handled, instead upon input of say, -10, the code gives me Square(-10). I can't seem to see what's wrong.
self.width = width, do you thing that there is something that will cause exception? Here python does n't care whetherwidthis negative or not. You have to take care of that.