Oli*_*ire 5 java exception-handling interface
假设我有以下可能无法修改的Java接口:
public interface MyInterface {
public void doSomething();
}
Run Code Online (Sandbox Code Playgroud)
现在实现它的类是这样的:
class MyImplementation implements MyInterface {
public void doSomething() {
try {
// read file
} catch (IOException e) {
// what to do?
}
}
}
Run Code Online (Sandbox Code Playgroud)
我无法从不读取文件中恢复.
一个子类RuntimeException可以明显帮助我,但我不确定这是否是正确的做法:问题是该异常将不会在类中记录,并且该类的用户可能会得到该异常解决这个问题.
我能做什么?
我们都同意:接口有问题.
我选择的解决方案
我最终决定编写一个MyVeryOwnInterface扩展MyInterface并添加作为错误方法签名的一部分MyRuntimeException:
public interface MyVeryOwnInterface extends MyInterface {
public void doSomething() throws MyRuntimeException;
}
class MyImplementation implements MyVeryOwnInterface {
public void doSomething() throws MyRuntimeException {
try {
// read file
} catch (IOException e) {
throw new MyRuntimeException("Could not read the file", e);
}
}
}
Run Code Online (Sandbox Code Playgroud)
你遇到了抽象漏洞的问题.没有真正好的解决方案,并且RuntimeException几乎可以使用你唯一能做的事情.
可以说,这也是为什么检查异常是失败概念的一个例子.