检测到错误时重新启动程序

时间:2015-09-01 03:05:26

标签: java exception-handling

我目前正在制作一个关于阅读文件的简单程序。我有一个尝试和catch块显示如下。我想要做的是如果程序检测到错误(异常),它将重新启动整个程序3次。之后,如果错误仍然发生,程序将自行终止,然后打印出异常消息。我让文件部分工作,但现在我不知道如何重新启动部分。感谢帮助,谢谢

这是我的代码:

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() {


        }

    }

2 个答案:

答案 0 :(得分:2)

这是我的解决方案:

private static int attempts = 1;
synchronized private static void retry() {
    if(attempts == 3)
        return;

    new Thread() {
        main(null);
    }.start();

    attempts++;
}

答案 1 :(得分:2)

您可以尝试以下方式,

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;
          } 
     }
}