2017-01-11 45 views
0

我在下面的代碼中使用lambda表達式,但即使該方法拋出一個檢查的異常,Eclipse也不需要用try,catch塊來包裝調用。爲什麼?爲什麼我不需要用try來包裝一個檢查過的異常?

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

} 
+4

因爲主要方法被聲明爲拋出它 –

回答

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

因爲你有一個main()條款throws。允許異常傳播,因此捕獲它不是必需的。刪除throws,您將需要添加一個try/catch。

相關問題