java为什么不要求我在这里用try,catch包装一个选中的异常?
我在下面的代码中使用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]));
}
}
# 1 楼答案
因为在
main()
上有一个throws
子句。允许该异常传播,因此不需要捕获它。删除throws
,你需要添加一个try/catch