Reputation: 752
Eclipse keeps telling me I need to handle IOExceptions from the 1 following line of code.
If I add a catch for IOException it tells me that the catch block will never be reached, while at the same time it still tells me to handle IOExceptions for that same line of code.
If I change ReadEvents to throw Exception instead, it will keep telling me to catch Exception.
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) {
}
Why is it impossible to handle that line?
Upvotes: 2
Views: 92
Reputation: 10059
The problem is that the catch statement must be in the Thread code, inside the lambda expression.
Try this:
Thread eventReadingThread = new Thread(() -> {
try{ ReadEvents(url, streamingMode); } catch (IOException e1) {}
});
Another (better) approach is to wrap ReadEvents
(btw very bad name!) and catch IOException
and then throw a subclass of RuntimeException
.
Doing this you won't need to use any try/catch block inside the lambda.
On the other hand, if you need to handle exceptions thrown by another Thread, you should register an implementation of the interface UncaughtExceptionHandler
.
For instance:
@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!
}
Upvotes: 6