Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I have been searching online to understand the usage of Exception.__init__(self) for user defined exceptions.

For example:

I have two user defined exceptions with one Exception.__init__(self) and second without.

class MyFirstError(Exception):

    def __init__(self, result):

        Exception.__init__(self)

        self.result = result

class MySecondError(Exception):

    def __init__(self, result):

        self.result = result

def test():

    try:

        raise MyFirstError("__My First Error__")

    except MyFirstError as exc:

        return exc.result

def test2():

    try:

        raise MySecondError("__ My Second Error__")

    except MySecondError as exc:

        return exc.result

if __name__ == "__main__":

    print(test())

    print(test2())

Output:

__My First Error__

__ My Second Error__

Both of them doing similar stuff. I couldn't understand the difference.

1 Answer

0 votes
by (25.1k points)

Using super().__init__() for Python3 or super(MyFirstError, self).__init__() for Python2 would be better.

In the first case you are calling the base Exception classes __init__ function, while in the second case you are overriding that __init__ function. Both ways are correct however, for your case you should just do this. 

class MyFirstError(Exception): pass

Browse Categories

...