我正在尝试添加throws
toString
的条款方法,但编译器说:
Exception IllegalAccessException is not compatible with throws clause in Object.toString()
这是我的代码:
public class NF {
private final Long id;
private final String name;
public static class Builder {
private Long id = null;
private String name = null;
// setters of id and name
public NF build() {
return new NF(this);
}
}
public NF(Builder b) {
this.id = b.id;
this.name = b.name;
}
public String toString() throws IllegalArgumentException, IllegalAccessException {
Field[] fields = this.getClass().getDeclaredFields();
String toString = "";
for (Field f : fields) {
String name = f.getName();
Object value = f.get(this); // throws checked exceptions
if (value != null)
toString += name.toUpperCase() + ": " + value.toString() + "%n";
}
return String.format(toString);
}
}
为什么我不能添加throws
至toString
?
最佳答案
重写方法时,不能抛出已检查异常,这些异常不是已出现在被重写方法的 throws
子句中的异常的子类。否则你就破坏了被重写方法的契约。
由于 Object
的 toString
不会抛出任何已检查异常,因此任何重写 toString()
的类都无法抛出已检查异常在那个方法中。您必须在内部捕获这些异常。
请注意,IllegalArgumentException
是一个 RuntimeException
异常,因此您仍然可以抛出它(您不必在 throws
中指定它)条款)。
另一方面,IllegalAccessException
是一个受检查异常,因此您必须在内部处理它。
public String toString() {
Field[] fields = this.getClass().getDeclaredFields();
String toString = "";
for (Field f : fields) {
try {
String name = f.getName();
Object value = f.get(this);
if (value != null)
toString += name.toUpperCase() + ": " + value.toString() + "%n";
}
catch (IllegalAccessException ex) {
// either ignore the exception, or add something to the output
// String to indicate an exception was caught
}
}
return String.format(toString);
}
关于java - 为什么 toString 不允许 throws 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48137381/