Reputation: 278
How would one go about overloading the getCause() method in a throwable object ? I have the following but it doesn't seem to work as it says that it cannot be overloaded with a string.
public class MyException extends RuntimeException {
String cause;
MyException(String s) {
cause = s;
}
@Overwrite public String getCause() {
return cause;
}
Upvotes: 0
Views: 1481
Reputation: 165
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
Upvotes: 1
Reputation: 47994
It is illegal to have two methods that only differ in their return type. Suppose someone wrote:
Object obj = myException.getCause();
That is perfectly legal java, and the compiler has no way to figure out if it's the String
version or the Throwable
version.
Likewise you can't replace the superclass signature since this is also perfectly legal:
Throwable t = new MyException();
Throwable t0 = t.getCause();
//Returns String?!?!?!?
Upvotes: 2