I've been trying to create a general trycatch method like this:
public static void tryCatchAndLog(Runnable tryThis) {
try {
tryThis.run();
} catch (Throwable throwable) {
Log.Write(throwable);
}
}
However I get an unhandled exception if I try to use it like this:
tryCatchAndLog(() -> {
methodThatThrowsException();
});
How can I implement this so that the compiler knows that tryCatchAndLog will handle the Exception?
Try this :
@FunctionalInterface
interface RunnableWithEx {
void run() throws Throwable;
}
public static void tryCatchAndLog(final RunnableWithEx tryThis) {
try {
tryThis.run();
} catch (final Throwable throwable) {
throwable.printStackTrace();
}
}
Then this code compiles:
public void t() {
tryCatchAndLog(() -> {
throw new NullPointerException();
});
tryCatchAndLog(this::throwX);
}
public void throwX() throws Exception {
throw new Exception();
}
Change Runnable to custom interface that is declared to throw Exception:
public class Example {
@FunctionalInterface
interface CheckedRunnable {
void run() throws Exception;
}
public static void main(String[] args) {
tryCatchAndLog(() -> methodThatThrowsException());
// or using method reference
tryCatchAndLog(Example::methodThatThrowsException);
}
public static void methodThatThrowsException() throws Exception {
throw new Exception();
}
public static void tryCatchAndLog(CheckedRunnable codeBlock){
try {
codeBlock.run();
} catch (Exception e) {
Log.Write(e);
}
}
}
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