为什么toString不允许throws子句

时间:2018-01-07 13:05:58

标签: java

我正在尝试将throws子句添加到toString方法,但编译器说:

  

异常IllegalAccessException与Ob​​ject.toString()中的throws子句不兼容

这是我的代码:

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

1 个答案:

答案 0 :(得分:2)

当您覆盖方法时,您不能抛出已检查的异常,这些异常不是已覆盖方法的throws子句中已出现的异常的子类。否则你就违反了被覆盖方法的合同。

由于Object' toString不会抛出任何已检查的异常,因此任何覆盖toString()的类都不能在该方法中抛出已检查的异常。你必须在内部捕获这些例外。

请注意,IllegalArgumentExceptionRuntimeException例外,因此您仍然可以抛出它(您不必在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);
}
相关问题