0

Question: Define a class Circle, whose objects are initialized with radius as it's attribute.

Ensure that the object creation raises RadiusInputError, a user defined exception, when the input radius is not a number.

Use try ... except clauses.

Create a Circle c1 using the statement c1 = Circle('hello'), and execute the script.

The error message "'hello' is not a number" should be displayed to user.

my code:

class RadiusInputError(Exception):
    pass

class Circle:
    def __init__(self,radius):
        self.radius=radius
        if type(self.radius) == "<class 'str'>":
            raise RadiusInputError

try:
    c1 = Circle('hello')
except RadiusInputError:
    print("'Hello' is not a number.")
sushanth
  • 8,275
  • 3
  • 17
  • 28
  • 1
    Instead of ``type`` its recommended to use ``isinstance`` to check object is of specific type, https://stackoverflow.com/questions/1549801/what-are-the-differences-between-type-and-isinstance, change the code to ``isinstance(self.radius, str)`` – sushanth Jun 09 '20 at 06:19
  • Still it doesn't give output: – Dilip Anand Jun 09 '20 at 06:29
  • What is the ouput your expecting ? – sushanth Jun 09 '20 at 06:32
  • ``""`` is a *string* containing the letters ````. The actual type is just ``str``. Use ``if type(self.radius) == str:`` or ``if isinstance(self.radius, str)``. Note that ideally, you should check for the desired type, not some undesired type - for example, a ``dict`` is likely unwanted here as well, but would pass your check. – MisterMiyagi Jun 09 '20 at 09:26

1 Answers1

0

I tryed to fix some issues. __init__ instead of init, type(self.radius) == str instead of type(self.radius) == "" Please try this code:

class RadiusInputError(Exception): 
    pass


class Circle: 
    def __init__(self, radius): 
        self.radius = radius 
        if type(self.radius) == str: 
            raise RadiusInputError


try: 
    c1 = Circle('hello') 
except RadiusInputError: 
    print("'Hello' is not a number.")
SimfikDuke
  • 943
  • 6
  • 21