在 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)
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP