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

EJS*_*EJS 3 java java-8

我一直在尝试创建一个像这样的通用 trycatch 方法:

public static void tryCatchAndLog(Runnable tryThis) {
    try {
        tryThis.run();
    } catch (Throwable throwable) {
        Log.Write(throwable);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试像这样使用它,则会得到一个未处理的异常:

tryCatchAndLog(() -> {
    methodThatThrowsException();
});
Run Code Online (Sandbox Code Playgroud)

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

Sxi*_*rik 5

尝试这个 :

@FunctionalInterface
interface RunnableWithEx {

    void run() throws Throwable;
}

public static void tryCatchAndLog(final RunnableWithEx tryThis) {
    try {
        tryThis.run();
    } catch (final Throwable throwable) {
        throwable.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后这段代码编译:

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

    tryCatchAndLog(this::throwX);

}

public void throwX() throws Exception {
    throw new Exception();
}
Run Code Online (Sandbox Code Playgroud)

  • 不过,我建议不要捕捉“Throwable”;除非您有充分的理由不这样做,否则捕获“异常”。 (2认同)