java - 接口(interface)实现启动不同的异常

标签 java oop exception interface

我有一个界面

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/

相关文章:

java - 使用个人 X509 证书连接到 Android 应用程序中受 SSL 保护的 API?

php - 以不区分大小写的方式实例化一个类

ruby - 使用 Ruby 进行面向对象设计

PHP_CodeSniffer 每个文件嗅探多个类

java - 计算数组中元素的总和

java - 是否值得在方法中使用位运算符?

java - 包装性能代码

php - 添加 Serialized 接口(interface)后,unserialize() 停止工作

python - 在 Python 字典中找不到键时会引发什么异常?

c# - ASP.NET 蓝屏死机 - 它从哪里获取堆栈跟踪?