RedRocket RedRocket - 4 months ago 11
Java Question

Relaunch application if there are exception in the program

I want to create a program that can relaunch itself if they detected any exception error during the execution.

Let say my program is trying reading a file. If the program failed to read a file, then it will have FileNotFound exception. After this exception occur, the program itself will restart and retry it again. This process will continue 3 times and if the program still cannot read that file, the program will then terminated and an exception message will be printed.

I created the read file part, but I have trouble to restart my program if it detect an error. Any help will be appreciated. I have included my pesudo code of what I am trying to do in the relaunch method.

fileReader.java

private static final int MAX_RETRIES = 3 ;
private static final int WAIT_BETWEEN_RETRIES_SEC = 30 ;

public static void main(String... args)
{
int retry = 1;
while (retry <= MAX_RETRIES) {
try {
//this method is okay, good. pass to next method.
readFile();

//error detected, retry only this method. Error fixed, pass to next method
method2();

//error detected, retry only this method. Error fixed, pass to next method
method3();
method4();
method5();


break;
} catch (IOException e) {
e.printStackTrace();
retry++;
try {
Thread.sleep(WAIT_BETWEEN_RETRIES_SEC * 1000);
} catch (InterruptedException e1) {}
}
}
if (retry == MAX_RETRIES) {
System.out.println("Failed!");
return;
}
// success
}

private static void readFile() throws IOException {
//read file code
}

Answer

instead of relaunching, you can (and should) handle this in main(). For example:

    private static final int MAX_RETRIES = 3 ;
    private static final int WAIT_BETWEEN_RETRIES_SEC = 30 ;

    public static void main(String... args) 
    {
        int retry = 1;
        while (retry <= MAX_RETRIES) {
            try {
                readFile();
                break;
            } catch (IOException e) {
                e.printStackTrace();
                retry++;
                try {
                    Thread.sleep(WAIT_BETWEEN_RETRIES_SEC * 1000);
                } catch (InterruptedException e1) {}
            }
        }
        if (retry == MAX_RETRIES) {
            System.out.println("Failed!");
            return;
        }
        // success
    }

  private static void readFile() throws IOException {
     //read file code
  }