Raising ValueError in a class

Viewed 24

Let's try this again as my previous post wasn't that clear. I'm a newbie in Python and I'm working on a school project. However I'm stuck on a small part of code.

#Goal

Raise a ValueError when class is called with the wrong arguments. Check argument age for float/int type and check if arguments is between 0 and 10.

Example:

class Dog():

    def __init__(self, name, age):
        self.name = name                     

        def check_arg(age):
            if isinstance(age, (int,float)) and age >= 0 and age <= 10:
                 return age
            else:
                 raise ValueError

        self.age = check_arg(age)

Now to check if it works I first put

henry = Dog("Henry", 10)
print(henry.age)

The results is printed: 10

Now I check if it is not true and put:

henry = Dog("Henry", 11)
print(henry.age)

Now I get the following:

Traceback (most recent call last):

File "c:\Folder\test.py", line 17, in henry = Dog("Henry", 11)

File "c:\Folder\test.py", line 12, in init self.age = check_arg(age)

File "c:\Folder\test.py", line 10, in check_arg raise ValueError

ValueError

So it does return a ValueError, but I think the function is handling it wrong. When I return instead of raise ValueError it shows: <class 'ValueError'>

Any tips?

1 Answers

I wish my teacher was as fast as you guys. But he said I could ignore the traceback bit. (spend hours trying to solve this)

raise ValueError()

was correct

Related