如何管理检查异常的实现

如何管理检查异常的实现

本文介绍了Java界面不声明任何异常。如何管理检查异常的实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下Java界面,我可能不会修改:

  public interface MyInterface {
public void doSomething();
}

现在执行它的类是这样的:

  class MyImplementation实现MyInterface {
public void doSomething(){
try {
//读取文件
} catch(IOException e){
//该怎么办?
}
}
}

我无法从没有阅读文件。



RuntimeException 的子类可以清楚地帮助我,但我不知道是否正确的事情:问题是那个异常然后不会被记录在类中,并且类的用户可能会得到这个异常对于解决这个问题一无所知。






我们都同意:界面有问题。



解决方案我选择



我终于决定写一个 MyVeryOwnInterface 扩展 MyInterface 并作为错误方法的签名的一部分添加 MyRuntimeException

  public interface MyVeryOwnInterface extends MyInterface {
public void doSomething()throws MyRuntimeException;
}
class MyImplementation实现MyVeryOwnInterface {
public void doSomething()throws MyRuntimeException {
try {
//读取文件
} catch(IOException e) {
抛出新的MyRuntimeException(无法读取文件,e);
}
}
}


解决方案

您已经遇到的问题。没有一个很好的解决方案,并且使用 RuntimeException 几乎是唯一可以做的。



可以说,这也是为什么检查异常是一个失败的概念的例子。


Let's say I have the following Java interface that I may not modify:

public interface MyInterface {
  public void doSomething();
}

And now the class implementing it is like this:

class MyImplementation implements MyInterface {
  public void doSomething() {
    try {
      // read file
    } catch (IOException e) {
      // what to do?
    }
  }
}

I can't recover from not reading the file.

A subclass of RuntimeException can clearly help me, but I'm not sure if it's the right thing to do: the problem is that that exception would then not be documented in the class and a user of the class would possibly get that exception an know nothing about solving this.

What can I do?


We all agree: the interface is faulty.

Solution I chose

I finally decided to write a MyVeryOwnInterface that extends MyInterface and adds as part of the signature of the faulty methods the 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);
    }
  }
}
解决方案

You've encountered the problem of leaky abstractions. There is no really good solution, and using a RuntimeException pretty much the only thing you can do.

Arguably, this is also an example for why checked exceptions are a failed concept.

这篇关于Java界面不声明任何异常。如何管理检查异常的实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 15:27