-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

user1545371
  • 13
  • 1
  • 3
  • 3
    Have a look over http://stackoverflow.com/questions/8362345/defining-one-global-uncaughtexceptionhandler-for-all-threads-of-my-application – Ioan Jun 06 '13 at 10:28
  • See: http://stackoverflow.com/questions/6662539/java-thread-exceptions There is a complete explanation and example code. – TFuto Jun 06 '13 at 10:56

1 Answers1

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");
        }
    });
Victor Sorokin
  • 11,878
  • 2
  • 35
  • 51