Super call in custom exception

16,198

Solution 1

Since a derived class always has the base class as a template, it is necessary to initialize the base class as the first step in constructing the derived object. By default, if no super call is made, Java will use a default (parameterless) constructor to create the base class. If you want a different constructor to be used, you have to use super to pass in the parameters you want and invoke the correct constructor.

In the case of custom exceptions, it is common to use super to initialize the exception's error message; by passing the message into the base class constructor, the base class will take care of the work of setting the message up correctly.

Solution 2

Because:

public MyException(String message)         
  {  
   //super() implicit call, how to set message???

}  

So you need a super(message) call to set the message.

Solution 3

It's just calling the base class constructor:

Exception(String message)

Constructs a new exception with the specified detail message.

Solution 4

The use of super is to call the constructor of the super(base, parent) class which happens to be the Exception class

Share:
16,198
Java_Alert
Author by

Java_Alert

Updated on July 18, 2022

Comments

  • Java_Alert
    Java_Alert almost 2 years

    I just want to know why we call super in own created custom exception.

    public class MyException extends Exception 
    { 
       public MyException(String message)         
      {  
        super(message);        
      }      
    }
    

    Here What is the use of calling super(message)

  • kavya
    kavya almost 5 years
    if we are calling super constructor so what is the use of customized exception?
  • Platinum Azure
    Platinum Azure almost 5 years
    Hi @kavya. The use of the customized exception is in making any changes compared to the base exception. A simple use case would be modifying the message before passing to the super() call. However, you could also define any variables or methods on the derived class, which a consumer could use to get more information.
  • truthadjustr
    truthadjustr almost 4 years
    Can you explain why there is no constructor in the Exception that accepts an int? I have a custom exception class but I could not throw it from a JNI C++ passing the int error code. But instead, I am compelled to instead use a String because the Exception class has a constructor that accepts a string.