Java 使用lambda表达式处理异常
我对lambda表达式有问题。我的代码:Java 使用lambda表达式处理异常,java,lambda,exception-handling,Java,Lambda,Exception Handling,我对lambda表达式有问题。我的代码: public static void main(String[] args) { Function<String, String> lambda = path -> { String result = null; try { BufferedReader br = new BufferedReader(new FileReader(path));
public static void main(String[] args) {
Function<String, String> lambda = path -> {
String result = null;
try {
BufferedReader br = new BufferedReader(new FileReader(path));
String line;
while ((line = br.readLine()) != null) {
result = result + line;
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
};
}
publicstaticvoidmain(字符串[]args){
函数lambda=路径->{
字符串结果=null;
试一试{
BufferedReader br=新的BufferedReader(新文件读取器(路径));
弦线;
而((line=br.readLine())!=null){
结果=结果+行;
}
}捕获(IOE异常){
e、 printStackTrace();
}
返回结果;
};
}
我现在试着编写这样的代码:
public static void main(String[] args) throws IOException {
Function<String, String> lambda = path -> {
String result = null;
BufferedReader br = new BufferedReader(new FileReader(path));
String line;
while ((line = br.readLine()) != null) {
result = result + line;
}
return result;
};
}
publicstaticvoidmain(字符串[]args)引发IOException{
函数lambda=路径->{
字符串结果=null;
BufferedReader br=新的BufferedReader(新文件读取器(路径));
弦线;
而((line=br.readLine())!=null){
结果=结果+行;
}
返回结果;
};
}
可能吗?我只能使用java.util.function。我试图从“lambda”中删除try-catch,我的“main”方法应该捕获该异常。内置的
函数
类不允许抛出未经检查的异常,从
但是,您可以轻松定义允许抛出异常的自己的异常,例如:
@FunctionalInterface
public interface CheckedFunction<U,V> {
public V apply(U u) throws Exception;
}
这将允许您的代码进行编译,但肯定不是一般推荐的最佳实践。正如dimo414所说,首先声明一个新的
请注意,在第一个解决方案中,您从未关闭
BufferedRead
,从而导致内存泄漏。“我只能使用java.util.function
”@MarkoTopolnik为什么?这是什么毫无意义的限制?您不能从java.util.function.function
抛出异常,lambda旨在支持定义您自己的函数接口。如果您想以示例代码中使用lambda的方式使用lambda,则需要使用不同的接口。
Function<Foo,Bar> f = foo -> {
try {
return foo.methodThatCanThrow();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
};
@FunctionalInterface
public interface CheckedFunction<U, V> {
public V apply(U u) throws IOException;
}
CheckedFunction<String, String> lambda = path -> {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.lines().collect(Collectors.joining());
}
};
CheckedFunction<String, String> lambda = path -> Files.lines(Paths.get(path)).collect(Collectors.joining());