Reputation: 389
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.
Upvotes: 0
Views: 93
Reputation: 21
What about this:
self.width = width
if self.width < 0:
raise ValueError('Width cannot be less than zero.')
Upvotes: 2
Reputation: 4490
Python does n't care whether width
is zero or not. You have to take care of that.
You may rewrite your code in this way.
class Square:
def __init__(self,width):
try:
if width < 0:
raise ValueError("Negative value of width")
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) + ")"
Upvotes: 2
Reputation: 131
You can try out this
class Square:
def __init__(self,width):
try:
if width < 0:
raise ValueError
self.width = width
except ValueError:
print("Width cannot be less than zero."),
print "Width is : %d" %width
def __repr__(self):
return 'Square({0})'.format(self.width)
def __str__(self):
return "Square(" + str(self.width) + ")"
obj = Square(10) # pass positive value
obj = Square(-10) # pass negative value
Upvotes: 2
Reputation: 109546
Your try block doesn't catch an error because there is nothing wrong with assigning a variable a negative value. You need to check for this yourself and raise the appropriate error.
def __init__(self, width):
if width < 0:
raise ValueError('Width cannot be less than zero.')
self.width = width
Upvotes: 3
Reputation: 46027
It's because negative width
is a valid number and assign it to self.width
does not raise ValueError
. Instead of handing exception you can do a simple if
check.
def __init__(self, width):
if width < 0:
print('Width cannot be less than zero.')
else:
self.width = width
Upvotes: 2