1

Friends see this simple code below. Note that I am using a thread pool, and thus I have no direct access to threads from my code.
In this code, there should be a NPE, but it completely disappears, and the code exits silently. I understand maybe exception stack is not available in main thread, but how in the world can display the occurence of a runtime exception? I am not interested in putting a try - catch(Exception e) all over the code since I cannot be sure where an NPE or runtime exception can occur. Runtime exceptions must be displayed before killing the JVM. But how? I have even put a try - catch(Exception) around main thread, but to no avail.

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class Test {

    ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(4);

    public static void main(String[] args) {
        new Test().execute();
    }

    void execute(){
        System.out.println("start");

        List<Callable<String>>li = new ArrayList<>();

        li.add(() -> {
            String s = null;
            s.toLowerCase();
            return "Hello";
        });

        try {
            List<Future<String>> cs = executor.invokeAll(li);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("end");
        executor.shutdown();
    }
}
Apurva Singh
  • 4,534
  • 4
  • 33
  • 42
  • The exception is lost because you don't call `get()` on the `List>` you get back from `invokeAll`. The exceptions are caught and propagated by the executor framework, but the point of propagation is the `get()` call, so you need to ensure you call it (you usually want to call `get()` anyways for other reasons such as getting the result of the calculation or ensuring it is finished). – BeeOnRope Dec 01 '17 at 19:34

1 Answers1

0

Look at Thread.setDefaultUncaughtExceptionHandler
This will call your handler when there is an uncaught exception

David Zimmerman
  • 335
  • 4
  • 7