【发布时间】:2018-11-18 00:36:22
【问题描述】:
我在处理异常时遇到了问题,在 lambdas 中没有使用 try 和 catch。
我找到了需要创建自己的Consumer 接口的示例代码,但它不起作用,我不知道如何修复它。
import java.util.function.Consumer;
@FunctionalInterface
public interface ThrowingConsumer<T, E extends Exception> {
void accept(T t) throws E;
static <T> Consumer<T> throwingConsumerWrapper(
ThrowingConsumer<T, Exception> throwingConsumer) {
return i -> {
try {
throwingConsumer.accept(i);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
};
}
}
这是我需要处理 IOException 的 lambda。必须从 main 抛出此异常。我不想在 main 中使用 try 和 catch。
public static void main(String[] args) throws IOException {
Function<String, List<String>> flines = fileName -> {
Scanner scanner;
ArrayList<String> wiersze = new ArrayList<>();
File f = new File(fileName);
scanner = new Scanner(f); // here :(
while (scanner.hasNext()) {
wiersze.add(scanner.nextLine());
}
scanner.close();
return wiersze;
};
}
我是 Java 新手,请您向我解释一下如何以最简单的方式解决此问题。
【问题讨论】:
-
没有
catching 就无法处理异常。 -
为什么不能使用
try和catch? -
我的教授说我必须换一种方式:/