通过接口了解Java中的异常

cen*_*980 0 java oop interface

我有以下代码,其中包含两个具有相同名称的两个方法的接口。但是,每种方法都会引发不同类型的Exception。

public interface xyz {
void abc() throws IOException;
}
public interface qrs {
void abc() throws FileNotFoundException;
}
public class Implementation implements xyz, qrs {
// insert code
{ /*implementation*/ }
}
Run Code Online (Sandbox Code Playgroud)

我知道在继承中,如果子类方法覆盖超类方法,则子类的throw子句可以包含超类的throws子句的子集,并且它一定不能抛出更多异常。但是,我不确定接口中如何处理异常。

对于abc()类中函数的实现Implementation,此方法可以引发两个异常还是仅引发一个异常?例如,以下方法有效吗?

public void abc() throws FileNotFoundException, IOException
Run Code Online (Sandbox Code Playgroud)

任何见解都表示赞赏。

chr*_*ke- 5

A class that implements an interface must satisfy all of the requirements of that interface. One requirement is a negative requirement--a method must not throw any checked exceptions except those declared with a throws clause on that interface.

FileNotFoundException是的特定类型(子类)IOException,因此,如果您的Implementation类声明void abc() throws FileNotFoundException,它满足qrs(仅允许该特定异常)和xyz(允许任何一种IOException)的要求。相反,事实并非如此。如果说了throws IOException,那不符合合同qrs