我正在尝试实现我的第一个自定义RuntimeException
:
public class MyException extends RuntimeException {
private static final long serialVersionUID = 1L;
private boolean isFizz;
private boolean isBuzz;
private Widget widget;
public class MyException(boolean isFizz, boolean isBuzz, Widget widget) {
super();
setIsFizz(isFizz);
setIsBuzz(isBuzz);
setWidget(widget);
}
// Getters and setters for all 3 properties...
@Override
public String toString() {
System.out.println("MyException is now in string form.");
}
}
当我去测试这个时:
MyException exc = new MyException(false, true, new Widget());
System.out.println(exc.toString());
System.out.println(exc.getMessage());
我得到:
MyException is now in string form.
null
所以getMessage()
行不通。我希望两者都toString()
生成getMessage()
相同的字符串,我认为这Throwable#getMessage()
只是简单地返回了toString()
.
所以我问:什么是“正常”的覆盖方式getMessage()
?我真的必须像这样覆盖它吗toString()
,就像这样:
@Override
public String getMessage() {
return toString();
}
或者,还有更好的方法?提前致谢。