接口和异常

Interfaces and exceptions

我在 tutorialspoint 上阅读有关接口的内容,发现了以下内容:

"Checked exceptions should not be declared on implementation methods other than the ones declared by the interface method or subclasses of those declared by the interface method."

谁能给我解释一下这到底是什么意思?

这意味着如果我声明的接口方法抛出一些已检查异常 E 而不是某些客户端代码使用接口应该显式处理此已检查异常(通过 try-catch 或进一步抛出)。如果您尝试在 class C 实现 I 中声明一些更多的已检查异常 (E1),这将破坏应用程序的逻辑:I 的客户不知道除了 E 之外抛出的异常。

实际上,编译器不允许你这样做

检查异常是必须在可能抛出它们的方法的类型签名中声明的异常。这句话的意思是,实现接口的 class 不应将任何已检查的异常添加到其从接口实现的方法的签名中。

所以如果你有这样的界面:

interface NoExceptions{
    void safeMethod();
}

禁止您这样声明 class:

class UnsafeClass{
    @Override
    void safeMethod() throws IOException{}
}

因为它正在修改类型签名。相反,这些异常应该在方法内部处理。

这是因为检查异常的目的是确保调用代码能够处理可能发生的问题。尝试在 subclass 中添加异常会移除安全性:

UnsafeClass uc = new UnsafeClass();
uc.safeMethod(); //Not allowed, because the exception is not handled
NoExceptions ne = uc;
ne.safeMethod(); //Becomes allowed, because the interface does not declare an exception

因此,您被禁止添加这样的例外。

但是,您可以编写一个实现,抛出接口上声明的已检查异常的子class。这将始终是一个安全的操作,因为 subclass 可以用作它的 superclass.

的直接替代品