Eclipse一直告诉我,我需要处理以下1行代码中的IOExceptions.
如果我为IOException添加一个catch它告诉我永远不会到达catch块,同时它仍然告诉我为同一行代码处理IOExceptions.
如果我改变ReadEvents而不是抛出异常,它将继续告诉我捕获异常.
public static void SetEventURL(String url, boolean streamingMode) throws Exception {
try {
Thread eventReadingThread = new Thread(() -> ReadEvents(url, streamingMode));
} catch (IOException e1) {
} catch (Exception e1) {
} catch (Throwable e1) {
}
Run Code Online (Sandbox Code Playgroud)
为什么不能处理那条线?
问题是catch语句必须在lambda表达式中的Thread代码中.
试试这个:
Thread eventReadingThread = new Thread(() -> {
try{ ReadEvents(url, streamingMode); } catch (IOException e1) {}
});
Run Code Online (Sandbox Code Playgroud)
另一个(更好的)方法是包装ReadEvents
(顺便说一下非常糟糕的名字!)并捕获IOException
然后抛出一个子类RuntimeException
.
这样做你不需要在lambda中使用任何try/catch块.
另一方面,如果需要处理另一个Thread抛出的异常,则应该注册接口的实现UncaughtExceptionHandler
.
例如:
@Test
public void test() {
Thread t = new Thread(() -> {throw new RuntimeException("Hi!");});
t.setUncaughtExceptionHandler((thread, throwable) -> System.err.println("Error!"));
t.start();//it'll print Error!
}
Run Code Online (Sandbox Code Playgroud)