-1

I am developing a java app I would like to know how to handle exceptions on multiple running threads. Is there any example? Thanks

2

1 Answer 1

0

If I understood your question correctly, you asking how to detect that thread finished due to unhandled exception.

You need to implement UncaughtExceptionHandler for that. The simplest useful activity you can put in your implementation of handler is to log exception which wasn't caught.

One sample of this, used together with Executor:

    final Thread.UncaughtExceptionHandler DEFAULT_HANDLER = new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            log.error("", e);
        }
    };

    ExecutorService executorService = Executors.newCachedThreadPool(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setUncaughtExceptionHandler(DEFAULT_HANDLER);
            return t;
        }
    });

    executorService.execute(new Runnable() {
        @Override
        public void run() {
            throw new RuntimeException("log me");
        }
    });

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.