Question: I use a the ExecutorService to execute my logic. As shown below , the run method should execute in a infinite loop. In short the run method is a message consumer which should remove messages from a queue and process the messages. However, the doSomething() method encounters an Exception, and never returns. After analysis, I realise that there was a NullPointer somewhere in the doSomething() method. While, I have taken care of that exception, how do I ensure that loop never terminates in-spite of any runtime exceptions. I cannot afford my Runnable task to be non-functional. It stops the entire functionality.

```
 ExecutorService service = Executors.newSingleThreadExecutor()
    service.submit(new Runnable(){
        public void run(){
          while(true){
           doSomething();
       }
    }
  })

```

Answer: 
Try catching exception within your loop like below:

```
ExecutorService service = Executors.newSingleThreadExecutor();
service.submit(new Runnable(){
    public void run(){
      while(true){
       try {
            doSomething();
       } catch (Exception e) {
           //log exception etc...
       }
   }
}
});

```
Just surround the run method's content with a try/catch that catches every exception.

```
 ExecutorService service = Executors.newSingleThreadExecutor()
    service.submit(new Runnable(){
        public void run(){
          while(true){
             try {
               doSomething();
             } catch (Exception e) {
               handleException();
             }
       }
    }
  })

```