如何在 Java 中使用 lambda 表示式處理異常?


 lambda 表示式體不能丟擲任何未在 函式式介面中指定過的異常。如果lambda 表示式可以 丟擲 異常,則函式式介面“throws”子句必須宣告相同的異常或其一個子型別。

示例

interface Student {
   void studentData(String name) throws Exception;
}
public class LambdaExceptionTest {
   public static void main(String[] args) {
      // lamba expression 
      Student student = name -> {
         System.out.println("The Student name is: " + name);
         throw new Exception();
      };
      try {
         student.studentData("Adithya");
      } catch(Exception e) {

      }
   }
}

輸出

The Student name is: Adithya

更新於:2020 年 7 月 10 日

3K+ 瀏覽量

開啟你的職業之旅

完成本課程,獲得認證

立即開始
廣告