Super call in custom exception
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
Java_Alert
Updated on July 18, 2022Comments
-
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 almost 5 yearsif we are calling super constructor so what is the use of customized exception?
-
Platinum Azure almost 5 yearsHi @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 almost 4 yearsCan 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 aJNI
C++
passing theint
error code. But instead, I am compelled to instead use aString
because the Exception class has a constructor that accepts a string.