Junior — Middle
Can a lambda expression in Java throw a checked exception?
sobes.tech AI
Answer from AI
A lambda expression in Java can throw a checked exception only if the functional interface it implements declares that exception in its method signature.
For example, if the interface method contains throws IOException, then the lambda can throw this exception. If the interface method does not declare checked exceptions, then the lambda cannot throw them.
Example:
@FunctionalInterface
interface IOFunction {
void run() throws IOException;
}
IOFunction func = () -> {
if (true) {
throw new IOException("Error");
}
};
If the interface does not declare exceptions, the compiler will not allow throwing checked exceptions inside the lambda.