The Java interface doesn't declare any exception. How to manage checked exceptions of the implementation?

老子叫甜甜 提交于 2019-12-05 08:57:18

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.

I'd throw a new IOError(e); and file an issue at the maintainer of the interface.

If you can't recover than you need to throw and thus wrap it into a RuntimeException or an Error and throw that.

public class Unchecked extends Error {

   private final Exception source;

   public Unchecked( Exception source) {
       this.source = source;
   }

   public String toString() {
       return "Unchecked Exception, Caused by: " + source;
   }

   public Exception getSource() {
       return source;
   }

   public static Unchecked wrap( Exception cause ) {
       return new Unchecked(cause);
   }
}

Clearly the interface designer is at fault for not considering the possibility that doSomething() may fail. Ideally he should have either allowed IOException to be thrown (if he suspected that IO wouldbe invovled) or a SomethingException (checked) which you could use to wrap your IOException.

If the interface designer is available to you, talk to them and ask what they expected to happen in the case of failure. Maybe they can change the interface: or maybe it is acceptable to fail silently according to the interface's contract.

Failing all of these you are reduced to a choice of failing silently (possibly recording but not responding to the problem) or throwing a RuntimeException which may terminate the process.

I don't think there is anything to do except to declare throws IOException in the interface. That is simply the nature of Java interfaces and checked exceptions.

You could have another method in your class (doSomethingDangerous) that throws the IOException. From the doSomething-implementation, you simply call doSomethingDangerous (wrapped in a try/catch) and then where ever you wish to be careful about doingSomething you call doSomethingDangerous directly.

I would suggest

throw new RuntimeException("while reading file " + fileName + "...", e);

Isn't the problem here, that the interface does not expect any problems at all?

(and you may want to create your own OurCompanyDomainException extends RuntimeException to make it easy to distinguish in the code on the other side of the interface).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!