简体   繁体   中英

Why aren't I required to wrap a checked exception with try, catch here?

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]));
    }

}
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM