我一直在尝试创建一个像这样的通用 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 将处理异常?
尝试这个 :
@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)
| 归档时间: |
|
| 查看次数: |
220 次 |
| 最近记录: |