为什么我不需要用try包装一个已检查的异常,赶上这里?

时间:2017-01-11 19:33:35

标签: java exception lambda

我在下面的代码中使用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 个答案:

答案 0 :(得分:4)

public static void main(String args[]) throws EmptyArrayException {

因为throws上有main()条款。允许异常传播,因此不需要捕获它。删除throws,您将需要添加try / catch。