我有一个界面
public interface DataDAO {
public void doSomething() throws Exception;
}
假设有两种实现,一种使用数据库获取数据,另一种使用 Web 服务。
public class DataDAOJdbc implements DataDAO {
public void doSomething() throws Exception {
//Implement
}
}
public class DataDAOWebService implements DataDAO {
public void doSomething() throws Exception {
//Implement
}
}
如您所见,问题出在启动的 super 通用异常上。因为两种实现都需要引发相同类型的异常。
Jdbc 实现实际上只抛出 SQLException 而 Webservice 实现只抛出 IOException。
问题是,如何使界面更优雅,从而捕获适当的异常?
我做的第一件事是创建我自己的异常,并在接口(interface)级别声明它
public interface DataDAO {
public void doSomething() throws MyCoolException;
}
然后,当然要相应地实现。
问题是,这有意义吗?我从来没有创建自己的异常(exception),所以我不确定这是否有意义。另外,创建 MyCoolException 时应该注意什么?
最佳答案
The first thing that I though was creating my own exception, and declare it on the interface level (...) does this make sense?
是的,它确实有道理,我认为这是处理这些情况的最佳方式。
我将为此提供一个启动示例(基于您当前的代码):
public class MyCoolException extends Exception {
public MyCoolException() {
}
public MyCoolException(String message) {
this.message = message;
}
}
public interface DataDAO {
public void doSomething() throws MyCoolException;
}
public class DataDAOJdbc implements DataDAO {
public void doSomething() throws MyCoolException {
//Implement
try {
} catch (SQLException e) {
//handle the exception
logger.error("Error!", e);
//throw your custom exception
throw new MyCoolException(e.getMessage());
}
}
}
public class DataDAOWebService implements DataDAO {
public void doSomething() throws MyCoolException {
//Implement
try {
} catch (IOException e) {
//handle the exception
logger.error("Error!", e);
//throw your custom exception
throw new MyCoolException(e.getMessage());
}
}
}
关于java - 接口(interface)实现启动不同的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16579438/