user3763074
user3763074

Reputation: 353

Raise a Value Error in Python When Creating a Class Instance?

Can I raise a value error if my class is not instantiated correctly?

This class needs to strip out any punctuation and return a string of just digits:

“(212) 555-4444” should return “2125554444” for example.

The test suite wants us to raise a ValueError if the string passed as a parameter has more or less than 10 digits...

I can figure out how to tell the number of digits, but what is the syntax for raising this error?

Do exceptions need their own methods inside the class? And if so, wouldn’t they need to be called to work?

Have tried searching for this answer everywhere (Stack Overflow, the docs, etc.) but I can’t seem to use the right language/terminology to explain it. Any help, even a link, would be appreciated. Thx

class Phone (object):

    #raise error here? 

    def __init__(self, phone_number):
        self.phone_number = phone_number
        #raise error here? 

    @property
    def number(self):
        punctuation = ['\'', '+', '(', ')', '-', 
        '.',',',' ']
        cpn = [item for item in self.phone_number if item not in punctuation]
        return ''.join(cpn)

    @property
    def area_code(self):
        return self.number[:3]

     #def raise_error_here?(self):
     #   pass

Upvotes: 1

Views: 3148

Answers (1)

DustyPosa
DustyPosa

Reputation: 463

I can't make sure that I had understand your question. If you want get below process:

>>> Phone(12345678910)
ValueError("...")

There have some ways to realize this that you expected. Like __new__ or __init__
In __init__:

class Phone (object):
    def __init__(self, phone_number):
        if len(phone_number) != 10:
            raise ValueError("...")
        self.phone_number = phone_number

    @property
    def number(self):
        punctuation = ['\'', '+', '(', ')', '-', 
        '.',',',' ']
        cpn = [item for item in self.phone_number if item not in punctuation]
        return ''.join(cpn)

    @property
    def area_code(self):
        return self.number[:3]

Upvotes: 1

Related Questions