ASm
ASm

Reputation: 389

My code isn't handling the exception (python)

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

Answers (6)

new 1234
new 1234

Reputation: 21

What about this:

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

Upvotes: 2

niyasc
niyasc

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

abhijeetmote
abhijeetmote

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

Sara Santana
Sara Santana

Reputation: 1019

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

Upvotes: 2

Alexander
Alexander

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

taskinoor
taskinoor

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

Related Questions