2015-03-25 36 views
0

我想写一个类来显示正方形的宽度,它将处理传递负数的异常。我的代码没有处理异常(python)

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

目前这个代码将会给正输入正确的输出,但异常没有被处理,经中说,-10输入相反,代码给我Square(-10)。我似乎无法看到有什么问题。

+0

你的代码不仅适用于积极的,但也是负面的。 – itzMEonTV 2015-03-25 05:45:46

+0

当你说'self.width = width'时,你有没有事情会导致异常?这里python不关心'width'是否为负值。你必须照顾这一点。 – niyasc 2015-03-25 05:45:54

回答

2

这是因为负width是一个有效的数字,并将其分配给self.width不会引起ValueError。不用处理例外情况,您可以执行简单的if检查。

def __init__(self, width): 
    if width < 0: 
     print('Width cannot be less than zero.') 
    else: 
     self.width = width 
2

Python不关心width是否为零。你必须照顾这一点。
你可以用这种方法重写你的代码。

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

您的尝试块不会捕获错误,因为将变量赋值为负值没有任何问题。你需要自己检查,并提出适当的错误。

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

你可以使用断言筹集错误:assert width>0,'error'

2

你可以尝试这个

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
2

这个怎么样:

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