Search code examples
pythontypeerrorexceptvalueerrorraiserror

Use 'try', 'raise', 'except' function to write a short program


Consider a Circle class used to represent circle objects. Instances of the Circle class will have an attribute called radius which indicates the size of the circle. The constructor method (e.g. init) for this class will initialise this attribute as usual.

Clearly, it doesn't make sense for a Circle object to have a size less than or equal to 0.

If someone attempts to create a Circle object with a negative or zero radius, then you should raise an exception of type ValueError. The ValueError object should be created with the following string:

Radius must not be less than or equal to 0

In addition, If someone attempts to create a Circle object with a non-integer valued radius, then you should raise an exception of type TypeError. The ValueError object should be created with the following string:

Radius must be an integer value

Define a Circle class with a constructor method that prevents Circle object being created with an invalid radius. The repr and str functions of this class should return the following string:

Circle(x)

where x is the radius of the circle.

For example:

def main():
    try:
      c = Circle(10)
    except ValueError as x:
      print("Error: " + str(x))
    else:
      print(c)
def __init__(self, x):
    try:
      if x <= 0:
        raise ValueError('Radius must not be less than or equal to 0')
      elif x != int or x != float:
        raise TypeError('Radius must be an integer value')
    except ValueError as x:
        print('Error: {0}'.format(x))
    except TypeError as x:
        print('Error: {0}'.format(x))
main()

The result should be:

Circle(10)

If c = Circle(-100), the result should be:

Error: Radius must not be less than or equal to 0

However, the part of "def init(self, x)" is incorrect. Can somebody please help?! Thanks!


Solution

  • Your code has a number of mistakes:

    First off, you say you want a "Circle class", but you don't actually define one. You must create a class Circle and move your __init__ inside of it.

    Second, this line is incorrect:

    elif x != int or x != float:
    

    I presume that your intention here was to make sure that x is either a float or an integer, and raise an error if it isn't. However, the way this is written, one of the two conditions will always be True: Either x is an integer so x != float is True, x is a float so x != int is True, or x is neither so they are both True.

    Modify the elif statement like so:

    elif not isinstance(x, (int, float)):
    

    Third, you probably need to switch the order of the if and elif, otherwise passing any non-numerical value to the constructor will cause the <= to throw an exception.

    Finally, you can turn those two excepts into one:

    except (ValueError, TypeError) as x:
    

    So the final result will be:

    class Circle:
        def __init__(self, x):
            try:
                if not isinstance(x, (int, float)):
                    raise TypeError('Radius must be an integer value')
                elif x <= 0:
                    raise ValueError('Radius must not be less than or equal to 0')
            except (ValueError, TypeError) as x:
                print('Error: {0}'.format(x))