假设在Java中,我正在使用一个相当普遍的预先存在的接口(interface)
public interface Generator {
public String generate();
}
我有自己的课
public class FromFileGenerator implements Generator {
...
public String generate() throws FileNotFoundException {
String output = //read from some file
return file;
}
}
Java编译器对我大吼,因为generate()的实现包含原始签名中未指定的异常(FileNotFoundException)。但是,显然,异常不属于接口(interface),但是在实现类中也不能忽略。如何解决这个问题而又不简单地无声无息地失败呢?
最佳答案
您可以将实现异常包装在未经检查的异常中,然后抛出该异常:
public class FromFileGenerator implements Generator {
...
public String generate() {
try {
String output = //read from some file
return file;
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
}