Restart a program in case of detected error

advertisements

I am currently making a simple program about reading a file. I have a try and catch block showed as below. What I want to do is if the program detected error (exception), it will relaunch the entire program 3 times. After that, if the error still occur, the program terminated by itself and then print out the exception message. I got the file part working, but now I have no idea how to do the relaunch part. Help will be appreciated, thanks

Here is my code:

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

 public class Test {

        public static void main(String args[]){

             try {
                    // constructor may throw FileNotFoundException
                    FileReader reader = new FileReader("someFile.txt");
                    int i=0;
                    while(i != -1){
                        //reader.read() may throw IOException
                        i = reader.read();
                        System.out.println((char) i );
                    }

                    reader.close();
                    System.out.println("--- File End ---");
                }

                //Relaunch program
                    retry();

                 catch (FileNotFoundException e) {
                    //do something clever with the exception
                    System.out.println("File not found");
                    e.printStackTrace();
                } catch (IOException e) {
                    //do something clever with the exception
                    e.printStackTrace();
                }

        }

        private static void retry() {

        }

    }


You can try following way,

public class Test {//Start class name with capital case

     public static void main(String args[]){
          int counter = 1;
          while(counter <= 3) {//try until counter reaches 3
              boolean isSuccess = readFile(counter++);
              if(isSuccess) {
                  break;
              }
          }
     }

     private static boolean readFile(int attempt) {
          try {
             //read file here
             return true;
           } catch(Exception e) {
             if(attempt == 3) {
                 e.printStackTrace();
             }
             return false;
          }
     }
}