在 Java lambda 表示式中使用異常時應遵守哪些規則?
lambda 表示式本身無法執行。它用於實現 函式式介面中宣告的方法。我們需要遵循一些規則才能在 lambda 表示式中使用異常處理機制。
lambda 表示式的規則
- lambda 表示式不能丟擲任何已檢查異常,除非其對應的 f函式式介面聲明瞭 throws 子句。
- lambda 表示式丟擲的異常可以是其 函式式介面的 throws 子句中宣告的異常的相同型別或子型別。
示例 -1
interface ThrowException { void throwing(String message); } public class LambdaExceptionTest1 { public static void main(String[] args) { ThrowException te = msg -> { // lambda expression throw new RuntimeException(msg); // RuntimeException is not a checked exception }; te.throwing("Lambda Expression"); } }
輸出
Exception in thread "main" java.lang.RuntimeException: Lambda Expression at LambdaExceptionTest1.lambda$main$0(LambdaExceptionTest1.java:8) at LambdaExceptionTest1.main(LambdaExceptionTest1.java:10)
示例 -2
import java.io.*; interface ThrowException { void throwing(String message) throws IOException; } public class LambdaExceptionTest2 { public static void main(String[] args) throws Exception { ThrowException te = msg -> { // lambda expression throw new FileNotFoundException(msg); // FileNotFoundException is a sub-type of IOException }; te.throwing("Lambda Expression"); } }
輸出
Exception in thread "main" java.io.FileNotFoundException: Lambda Expression at LambdaExceptionTest2.lambda$main$0(LambdaExceptionTest2.java:9) at LambdaExceptionTest2.main(LambdaExceptionTest2.java:11)
廣告