I am working on a small helper that is supposed to invoke arbitrary code (passed in as lambda). The helper should catch certain exceptions, and throw them inside some wrapper. My "own" exceptions should not be wrapped but just re-thrown.
I came up with this code:
@FunctionalInterface
interface Processable<T, X extends Throwable> {
public T apply() throws X;
}
class MyCheckedException extends Exception { ... }
class MyCheckedExceptionWrapper extends MyCheckedException { ... }
public class MyExceptionLogger<T, X extends Throwable> {
public T process(Processable<T, X> processable) throws MyCheckedException {
try {
return processable.apply();
} catch (MyCheckedException thrown) { // this line isn't accepted
throw thrown;
} catch (Exception | LinkageError thrown) {
throw new MyCheckedExceptionWrapper(thrown);
} catch (Throwable thrown) {
... just log
return null;
}
}
}
The above gives a compile error:
Unreachable catch block for MyCheckedException. This exception is never thrown from the try statement body MyExceptionLogger ...
In other words: although apply()
is defined to throw some X extends Throwable
I can't catch a specific checked exception when invoking that method.
I know that I can get to working code by catching Throwable, to then use instanceof
checks - but I would like to understand why it is not possible to have a try/catch as outlined above.