1

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.

PGS
  • 1,046
  • 2
  • 17
  • 38

2 Answers2

2

More correct syntax would be super().__init__() for Python3 or super(MyFirstError, self).__init__() for Python2.

You typically do this when override __init__() in a subclass and need base class constructor to be called as well. In your particular case there's no any benefit of calling base Exception constructor with no parameters as it's not doing anything fancy, but you may want to pass the result to the Exception constructor so that you don't have to keep self.result yourself in a subclass.

Example:

class MyFirstError(Exception):
    def __init__(self, result):
        super().__init__(result)  # will pass result as an argument to the base Exception class

Though, same thing could be also done in much shorter way:

class MyFirstError(Exception): pass

As you don't implement the constructor, base Exception's __init__(result) method will be implicitly called achieving exactly the same result as above.

Vovan Kuznetsov
  • 461
  • 1
  • 4
  • 10
0

Using Exception.__init__(self) is nothing but calling the parent class Exception in the sub class to handle the situation in case any error occurs such that the program flow wouldn't be disrupted because of this exception. And if you ask me for the difference between using __init__ of Exception class and not using the __init__ of Base Class : Exception , I'd Demonstrate the following Example below:

class Example_Exception:
      def __init__(self,length,atleast):
        Exception.__init__(self):
         self.length=length
         self.atleast=atleast
 try:
      text=input()
      if len(text)<3:
        raise Example_Exception(len(text),3)
 except Example_Exception as ex:
      print(('entered too less letters for a text ,length entered:
      {0} , expected length : {1}').format(ex.length,ex.atleast))
 else:
      print('No Exception')

In the above snippet of code, if you could see we want extra functionality to make user know that he had entered less number of letters for text than the required number (3 in our case), so we have called base class initializer Which is the Exception class and later implemented the extra functionality we want our code to exhibit (printing the cause for exception in our case).

ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257