-1

My function looks like:

void Foo() throws Exception {
...
}

I'm then calling this method in other method's parameter:

Bar( () -> Foo());

And Bar() looks like this:

void Bar(Runnable method) {
    try {
        method.run()
    } catch (Exception e) {
    ...
    }
}

Earlier I had Foo() throwing RuntimeException so it worked, but when i changed it to throw Exception compiler won't allow me to run my code indicating its uncaught exception. I have to use checked exception so going back to Runtime is not an option.

SOLUTION based on this solution Java 8 Lambda function that throws exception? I have used try catch block in this call

Bar( () -> { try { Foo(); } catch (Exception e) { }; } );

Thanks for help anyway

Community
  • 1
  • 1
vul6
  • 441
  • 4
  • 14

2 Answers2

0

I will interpret your question, as to why you have to use a checked Exception in the second case. (If this is not your question please edit it accordingly)

A RuntimeException is any Exception that can not be fixed at runtime (like a NullPointerException), so that's why the compiler doesn't complain when you don't catch it. You still can catch a RuntimeException though.

So when you change it to a normal Exception the compiler then thinks, that this is something you should catch every time, because it may be fixable at runtime.

reckter
  • 586
  • 5
  • 12
  • Yes, I know it, but what can I do about that? Calling Bar( () -> Foo()); is now impossible unless I change Foo() to not throwing Exception? – vul6 Feb 20 '15 at 12:28
  • 1
    It's not impossible, you just have to handle the Exception that it throws with a `try` block. – reckter Feb 20 '15 at 12:33
0

It doesn't work because Runnable.run() is not declared to throw Exception.

xehpuk
  • 7,814
  • 3
  • 30
  • 54