I know Runnable does not throw Exception, so I am trying to write a new interface that accepts method that can throw checked exception:
Interface:
interface MyInterface {
void run() throws Exception;
}
Service:
public void serviceMethod(MyInterface action) throws Exception {
// ...
action.run();
// ...
}
public void serviceMethod(Runnable action) { // for methods don't throw checked exception
// ...
action.run();
// ...
}
Main:
public void myMethod() throws Exception {
service.serviceMethod(this::someMethodThatThrowsCheckedException);
service.serviceMethod(this::someMethodThatDoesNotThrowCheckedException);
}
This all seems OK, but I don't want myMethod() to throw the base class Exception, I want it to throw the actual exception classes throw by someMethodThatThrowsCheckedException. e.g. if
public void someMethodThatThrowsCheckedException throws IOException, ClassNotFoundException {//...}
Then I want myMethod() to throw IOException, ClassNotFoundException, instead of Exception. Just like the case when the method is called normally without going through the interface:
public void myMethod() throws IOException, ClassNotFoundException {
someMethodThatThrowsCheckedException();
}
Can this be done in a generic way?
And one that not throws
usage:
One for throws:
One for no throws:
Hope this will help you