Reputation: 691
I use lambda expressions in the following code but even though the method throws a checked exception Eclipse doesn't require that I wrap the call with try, catch blocks. Why?
package lambda;
//Throw an exception from a lambda expression.
interface DoubleNumericArrayFunc {
double func(double[] n) throws EmptyArrayException;
}
class EmptyArrayException extends Exception { // Checked exception
}
public class LambdaExceptionDemo {
public static void main(String args[]) throws EmptyArrayException {
DoubleNumericArrayFunc average = (n) -> {
if (true)
throw new EmptyArrayException();
return 1;
};
// Why try catch isn't required here?
System.out.println("The average is " + average.func(new double[0]));
}
}
Upvotes: 0
Views: 44
Reputation: 361585
public static void main(String args[]) throws EmptyArrayException {
Because you have a throws
clause on main()
. The exception is allowed to propagate, so catching it isn't required. Delete the throws
and you'll be required to add a try/catch.
Upvotes: 4