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

时间:2016-12-23 11:22:25

标签: java java-8

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

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

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

tryCatchAndLog(() -> {
    methodThatThrowsException();
});

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

2 个答案:

答案 0 :(得分:4)

将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);
        }
    }

}

答案 1 :(得分:4)

试试这个:

@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();
}