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);
}
}
}
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.
There are mainly two types of exceptions: checked and unchecked.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With