Reputation: 75
Can anyone please explain why we should have constructors like below when defining custom exceptions :
public MyException(Throwable cause) {
super(cause);
}
public MyException(String message, Throwable cause) {
super(message, cause);
}
Upvotes: 4
Views: 585
Reputation: 3171
As mentioned in your question one should implement the above mentioned constructors to the MyException
class which is a subclass of Exception
But it is not absolutely mandatory to have only those constructors.
You can very well have the following constructors which do not have Throwable
as parameters:
public MyException() {
super();
}
public MyException(String message) {
super(message);
}
But these constructors have a drawback associated. consider the following code say suppose in class MyClass
:
public static void myMethod() throws MyException{
//Some code
}
Now in some code you call this myMethod()
as show below:
try{
MyClass.myMethod();
} catch (MyException e){
e.getCause();
}
If you used the constructor with the constructors stated in my answer the e.getCause()
would return null
. So it would be difficult to ascertain what is the exact cause of the exception.
Upvotes: 1
Reputation: 393811
It allows you to add to your custom Exception instance information regarding the reason of throwing that exception.
It is useful when you catch one exception and throw another.
For example :
try {
....
}
catch (SomeException ex) {
throw new MyException ("some message", ex);
}
Upvotes: 3