Francesco Urdih
Francesco Urdih

Reputation: 115

Cleanly stop execution if exception happens, Java

I have a Runnable that works with files. The first thing I do in the run method is calling an openFile method which, of course, could throw an exception and I want the thread to stop if this happens.

Assuming this is the code:

public void run(){
    try{
        openFile();
    } catch(IOException e){
        //do some stuff, like log
        return;
    }
    /*
    other stuff
    */
}

I'd like to stop the thread internally in the openFile method to make the code cleaner (unless it's a bad practice, I don't know).

I could do something like this:

public void run(){
    openFile();
    /*
    other stuff
     */
}

public void openFile(){
    try{
        //some stuff to open the file
    } catch(IOException e){
        //do some stuff, like log
        throw new //some RuntimeException
    }
}

But by doing this way I would show the Exception on stderr and I want to avoid it (I have the log for that).

So, is there a way to obtain a cleaner code in the run without dirtying the stderr?

Upvotes: 0

Views: 148

Answers (1)

Juan
Juan

Reputation: 2084

I think your best bet, if youre using Java 8 or above is to rely on ExecutorService to manage the threads of your application. Here is an example:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {

    public static void main(String[] args) {
        ExecutorService executor = null;
        try {
            executor = Executors.newSingleThreadExecutor();
            executor.execute(() -> openFile());
        } finally {
            if (executor != null) {
                executor.shutdown();
            }
        }
    }

    private static void openFile() throws RuntimeException {
        // Do stuff, maybe throw exception
    }
}

To stop the thread call executor.shutdown() which rejects any new tasks submitted to the thread executor while continuing to execute any previously submitted tasks.

Upvotes: 1

Related Questions