0

I have one method which throws checked exception:

private void testCacheExpiration() throws InterruptedException

I am trying to create a generic wrapper that will handle the exception gracefully.

private Runnable handleNonTestException(Runnable r) {
    return () -> {
        try {
            r.run();
        } catch (Exception e) {
            logger.error(NON_TEST_EXCEPTION_MSG, e);
            errors.add(new Error(e.getMessage(), NON_TEST_EXCEPTION_MSG));
        }
    };
}

Now I am using handleNonTestException(this::testCacheExpiration) which gives me compile time error unhandled exception type: InterruptedException . What may I be missing?

Sagar
  • 5,315
  • 6
  • 37
  • 66

1 Answers1

0

My testCacheExpiration method signature doesn't conform to the run method's signature in runnable interface (which doesn't throw any exception)

Following changes solved it:

@FunctionalInterface
private interface ThrowingRunnable <E extends Exception> {
    void run() throws Exception;
}

private Runnable handleNonTestException(ThrowingRunnable<? extends Exception> r) {
    return () -> {
        try {
            r.run();
        } catch (Exception e) {
            logger.error(NON_TEST_EXCEPTION_MSG, e);
            errors.add(new Error(e.getMessage(), NON_TEST_EXCEPTION_MSG));
        }
    };
}`
Sagar
  • 5,315
  • 6
  • 37
  • 66