I am trying to add throws
clause to a toString
method but the compiler says:
Exception IllegalAccessException is not compatible with throws clause in Object.toString()
Here is my code:
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);
}
}
Why can't I add throws
to toString
?