-4

I'm learning Java and am a bit confused, why Lambda Expressions can't throw checked exceptions. Anyone has an understandable explanation for this?

I read through this post: Java 8 Lambda function that throws exception? and this one: java throwing checked exceptions? but both werent helping me. I also read multiple articles on google, but they all say that its not possible, but not why.

hallo545401
  • 115
  • 13
  • 4
    The first question you link to shows that *a lambda can in fact throw a checked exception*. Did you read it? – ernest_k Jul 09 '20 at 06:48

1 Answers1

1

It's pretty much a method. If the method signature is declared to throw a checked exception, then a checked exception can be thrown inside of the lambda.

Imagine if you could.

Runnable r = ()->{ throw new CheckedException();};

Now our imaginary runnable.run can be called, but the caller will not know it has to handle a checked exception.

Callable on the other hand does throw an Exception.

Callable c = ()->{ throw new CheckedException();};

This works fine, because Callable.call is declared to throw an exception. You don't know the specific type of exception, but you have to handle one.

matt
  • 10,892
  • 3
  • 22
  • 34