Accepted answer clears the point :
It is illegal to have two methods that only differ in their return
type
But if you have a situation where, getCause()
should return the custom cause in MyException
, in case original cause is null.
In that case, you can use initCause()
to set the cause and override toString()
method. So, when getCause()
method will be called on object of MyException
, it will show the message from customCause instead of null.
What is the use: In legacy system, if you have used getCause()
on MyException
object while logging, and now you want to add the custom cause to it without changing lot of code, here is the way.
public class MyException extends RuntimeException {
String customCause;
MyException(String s) {
super(s);
customCause = s;
}
@Override
public synchronized Throwable getCause() {
if (super.getCause() != null) {
return this;
} else {
this.initCause(new Throwable(customCause));
return this;
}
}
@Override
public String toString() {
String s = getClass().getName();
String message = getLocalizedMessage();
if (message == null) {
message = customCause;
}
return (message != null) ? (s + ": " + message) : s;
}
}
References:
https://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#initCause(java.lang.Throwable)
https://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html