Search code examples
pythonooptry-catchinitexcept

OOP / try except statements in __init__ of class


I want to control the input of the class Webpage. Meaning, I want to be sure that the webpage's link is appropriately provided, e.g. 'http://example.com'.

class Webpage(object):
    def __init__(self, link):
        prefix = ['http', 'https']
        suffix = ['com', 'net']
        try:
            if link.split(':')[0] in prefix and link.split('.')[-1] in suffix:
                self.link = link
        except:
            raise ValueError('Invalid link') 


   def get_link(self):
        '''
        Used to safely access self.link outside of the class

        Returns: self.link
        '''
        return self.link

   def __str__(self):
        return str(self.link)  

However, when I try code:

test_link = Webpage('example.com')

I do not get ValueError, as I would expect. Call of methods:

test_link.get_link()
print(test_lint)

result in

AttributeError: 'Webpage' object has no attribute 'link'

which indicates that try/except worked partially - try did not execute self.link = link, however except statement wasn't executed.

An example:

test_link = Webpage('http://example.com')

works fine with get_link() and print methods of that class.

Will appreciate any hint.


Solution

  • Raising an expection as in your case ValueError is done in the try block and handling of the expection it is done in the except block

    For more information please visit Raising Expections in python

    class Webpage(object):
        def __init__(self, link):
            prefix = ['http', 'https']
            suffix = ['com', 'net']
            try:
                if link.split(':')[0] in prefix and link.split('.')[-1] in suffix:
    
                    self.link = link
                else:
                    raise ValueError('Invalid link')
            except ValueError as exp:
                print("the value error is {}\nthe link specified is {} ".format(exp,link))
    
    
    
        def get_link(self):
            '''
            Used to safely access self.link outside of the class
    
            Returns: self.link
            '''
            return self.link
    
        def __str__(self):
            return str(self.link) 
    
    test_link = Webpage('example.com')
    

    Output

    the value error is Invalid link
    the link specified is example.com
    

    Hope this helps