How to properly catch RuntimeExceptions from Executors?

前端 未结 5 1855
青春惊慌失措
青春惊慌失措 2020-12-12 20:44

Say that I have the following code:

ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(myRunnable);

Now, if <

5条回答
  •  孤城傲影
    2020-12-12 21:34

    Decorate the runnable in another runnable which catches the runtime exceptions and handles them:

    public class REHandler implements Runnable {
        Runnable delegate;
        public REHandler (Runnable delegate) {
            this.delegate = delegate;
        }
        public void run () {
            try {
                delegate.run ();
            } catch (RuntimeException e) {
                ... your fancy error handling here ...
            }
        }
    }
    
    executor.execute(new REHandler (myRunnable));
    

提交回复
热议问题