【问题标题】:Java Lambda Exception HandlingJava Lambda 异常处理
【发布时间】: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 就无法处理异常。
  • 为什么不能使用trycatch
  • 我的教授说我必须换一种方式:/

标签: java exception lambda


【解决方案1】:

那么您的问题是您有一段代码会引发检查异常,并且您希望它成为Function 对象的实现吗?您在某处找到了如何为Consumer 执行此操作,您只需要Function 的代码适配器?

假设重写应该是这样的:

import java.util.function.Function;

@FunctionalInterface
public interface ThrowingFunction<T, R, EXC extends Exception> {
    R apply(T t) throws EXC;

    static <T> Function<T> throwingFunctionWrapper(
       ThrowingFunction<T, R, Exception> throwingFunction
    ) {
        return t -> {
            try {
                return throwingFunction.apply(t);
            } catch (Exception exc) {
                throw new RuntimeException(exc);
            }
        };
    }
}

更笼统地说,throwingFunctionWrapper 可以是:

static <T> Function<T> throwingFunctionWrapper(
   ThrowingFunction<T, R, ? extends Exception> throwingFunction
) {

为了处理异常,您应该继承RuntimeException,然后只捕获该类,以免解开任何其他运行时异常。

解包(使用原始代码)为:

try {
   ...
} catch (RuntimeException exc) { // subclass me !!
   throw (IOException)exc.getCause();
}

【讨论】:

    猜你喜欢
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    相关资源
    最近更新 更多