0

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.

2
  • you code not only works for positive but also negative. Commented Mar 25, 2015 at 5:45
  • When you say self.width = width, do you thing that there is something that will cause exception? Here python does n't care whether width is negative or not. You have to take care of that. Commented Mar 25, 2015 at 5:45

6 Answers 6

3

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

2

you can use assert for raising error: assert width>0,'error'

Comments

2

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

Comments

2

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) + ")"

Comments

2

What about this:

    self.width = width
    if self.width < 0:
        raise ValueError('Width cannot be less than zero.')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.