我需要一些帮助来了解这种情况下的最佳实践。
我创建了一个自定义的异常类,该异常类具有3个子类。我正在覆盖消息以适合我的需要。
现在,子类也需要具有自定义消息。我能以某种方式找到一种利用父类但格式不同的方法吗?
家长异常(exception)类别
public class customException extends RuntimeException {
String myFormat = " Custom Exception message here , %s, %s";
private String A;
public customException(String A, String message){
this.A= A;
super(message);
}
@Override
public String getMessage() {
return String.Format(myFormat, A, super.getMessage());
}
子异常类示例public class childException extends customException {
String myFormat = " ChildException message here , %s, %s";
public customException(String A, String message){
super(A, message);
}
@Override
public String getMessage() {
return super.getMessage(); // find a way to format using the ChildClass myFormat?
}
编辑:解决方法我目前看起来像这样。
子异常类示例
public class childException extends customException {
String myFormat = " ChildException message here , %s, %s";
private String A;
public customException(String A, String message){
super(message); // have another constructor in the Parent exception class
this.A=A;
}
@Override
public String getMessage() {
return String.Format(myFormat, A, super.getMessage());
}
为了避免上面的super.getMessage(),也要打印父异常的格式,因此我检查了父类(super class)中的getMessage()方法,以查看该类是否为子类的实例。不适合的解决方案。@Override
public String getMessage() {
if( this instanceOf childException)
return super.getMessage();
else
return String.Format(myFormat, A, super.getMessage());
}
最佳答案
为什么不更改childException类中的return super.getMessage()行。
代替:
@Override
public String getMessage() {
return super.getMessage(); // find a way to format using the ChildClass myFormat?
}
尝试:@Override
public String getMessage() {
this.myFormat = this.myFormat.append("hello");
return this.myFormat; // find a way to format using the ChildClass myFormat?
}
关于java - 格式化自定义错误消息的基本问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65684499/