java - 为什么 toString 不允许 throws 子句

标签 java

我正在尝试添加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);
    }

}

为什么我不能添加throwstoString

最佳答案

重写方法时,不能抛出已检查异常,这些异常不是已出现在被重写方法的 throws 子句中的异常的子类。否则你就破坏了被重写方法的契约。

由于 ObjecttoString 不会抛出任何已检查异常,因此任何重写 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/

相关文章:

java - 如何为 IntelliJ IDEA 正确安装 Google Java Format 插件?

java - 为什么数组元素必须是同一类型

java - 多态性 vs 覆盖 vs 重载

java - Runtime.getRuntime().gc() 在 Java 8 中继续存在,有什么用处或者有什么区别吗?

java - 如何在 Gradle 构建中指定所需的 Java 版本?

Java 访问者模式同时适用于原始类型和类

java - JUnit 测试事务方法

java - 数据的 session.update() 或 session.save() 没有反射(reflect)在数据库中?

java - 为什么我们在 Comparable 实现中的 CompareTo 中使用 `this`?

java - 了解 java.io 库