我在下面的代码中使用lambda表达式,但即使该方法抛出一个已检查的异常,Eclipse也不要求我用try,catch块包装调用。为什么呢?
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]));
}
}
答案 0 :(得分:4)
public static void main(String args[]) throws EmptyArrayException {
因为throws
上有main()
条款。允许异常传播,因此不需要捕获它。删除throws
,您将需要添加try / catch。