javaexceptionlambdachecked-exceptionsunchecked-exception

Why can't Java Lambda throw an checked exception


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.


Solution

  • 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.