Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
    }
  }
}
like image 227
Olivier Grégoire Avatar asked Apr 29 '10 16:04

Olivier Grégoire


People also ask

What is an exception how the exceptions are handled in Java?

Java Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc. Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program's instructions.

How many ways we can handle exceptions in Java?

There are mainly two types of exceptions: checked and unchecked.

Can we override checked exception?

An overriding method can throw any unchecked exceptions, regardless of whether the overridden method throws exceptions or not. However, the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method.


1 Answers

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.

like image 113
Michael Borgwardt Avatar answered Nov 09 '22 21:11

Michael Borgwardt