Use Of Exception.__init__(self) For User Defined Exceptions
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.__
Solution 1:
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.
Post a Comment for "Use Of Exception.__init__(self) For User Defined Exceptions"