是否可以使用lambda表达式在java中实现一个通用的try-catch方法?

是否可以使用lambda表达式在java中实现一个通用的try-catch方法?,java,java-8,Java,Java 8,我一直在尝试创建一个通用的trycatch方法,如下所示: public static void tryCatchAndLog(Runnable tryThis) { try { tryThis.run(); } catch (Throwable throwable) { Log.Write(throwable); } } tryCatchAndLog(() -> { methodThatThrowsException();

我一直在尝试创建一个通用的trycatch方法,如下所示:

public static void tryCatchAndLog(Runnable tryThis) {
    try {
        tryThis.run();
    } catch (Throwable throwable) {
        Log.Write(throwable);
    }
}
tryCatchAndLog(() -> {
    methodThatThrowsException();
});
但是,如果我尝试像这样使用它,我会得到一个未处理的异常:

public static void tryCatchAndLog(Runnable tryThis) {
    try {
        tryThis.run();
    } catch (Throwable throwable) {
        Log.Write(throwable);
    }
}
tryCatchAndLog(() -> {
    methodThatThrowsException();
});

如何实现这一点,以便编译器知道tryCatchAndLog将处理异常?

将Runnable更改为声明为引发异常的自定义接口:

public class Example {

    @FunctionalInterface
    interface CheckedRunnable {
        void run() throws Exception;
    }

    public static void main(String[] args) {
        tryCatchAndLog(() -> methodThatThrowsException());
        // or using method reference
        tryCatchAndLog(Example::methodThatThrowsException);
    }

    public static void methodThatThrowsException() throws Exception {
        throw new Exception();
    }

    public static void tryCatchAndLog(CheckedRunnable codeBlock){
        try {
            codeBlock.run();
        } catch (Exception e) {
            Log.Write(e);
        }
    }

}
试试这个:

@FunctionalInterface
interface RunnableWithEx {

    void run() throws Throwable;
}

public static void tryCatchAndLog(final RunnableWithEx tryThis) {
    try {
        tryThis.run();
    } catch (final Throwable throwable) {
        throwable.printStackTrace();
    }
}
然后,此代码编译:

public void t() {
    tryCatchAndLog(() -> {
        throw new NullPointerException();
    });

    tryCatchAndLog(this::throwX);

}

public void throwX() throws Exception {
    throw new Exception();
}

不过,我建议不要捕捉可丢弃的
;catch
异常
除非您有充分的理由不这样做。好吧,我们在同一时间键入了相同的答案:)是的+1给你:)