0

I want to restart the program after throwing an exception this my code

    System.out.println("please enter an intger to compute its factorial:");
    BufferedReader bufferedreader = new BufferedReader( new InputStreamReader(System.in)); 
    String number ="";
    try {
        try {
            number = bufferedreader.readLine();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }

    intN=Integer.parseInt(number);
        if (intN > 0) {         // from the command line
            FactorialIter f = 
                new FactorialIter(Math.abs(intN));

        }
    } catch (NumberFormatException e) {
        // TODO Auto-generated catch block
        System.out.println("error you should enter a number");
        throw new MyExceptions("try again please use integer numbers");
        //if possible to restart the main 

    }

so when ever the user enters a character the program will throws an exception and then restarts is this possible??

Mabulhuda
  • 57
  • 1
  • 6
  • Try checking this question: http://stackoverflow.com/questions/4159802/how-can-i-restart-a-java-application – DrRoach Nov 17 '14 at 13:58

2 Answers2

2

In general, one should not be invoking main recursively, especially for the purpose of restarting the program.

If you want to go back to a certain point in your program, use a loop. Here is one example of how you can do it:

boolean done = false;
do {
    done = true;
    try {
         ...
    } catch (NumberFormatException e) {
        System.out.println("error you should enter a number");
        done = false;
    }
} while (!done);

The loop will continue from the beginning each time the exception handler sets done to false.

Sergey Kalinichenko
  • 675,664
  • 71
  • 998
  • 1,399
0

You could just put it in a loop.

 While(isValid != TRUE)
 {
      try
      {
           try {
                 number = bufferedreader.readLine();
           } catch (IOException e) {
               // TODO Auto-generated catch block
                e.printStackTrace();
           }

           intN=Integer.parseInt(number);
           if (intN > 0) {         // from the command line
                  FactorialIter f = 
                         new FactorialIter(Math.abs(intN));
               isValid = TRUE;

           }

      }
      catch (NumberFormatException e)
      {
           System.out.println("error you should enter a number");
           System.out.println("try again please use integer numbers");
           isValid = FALSE;
      }

 }
Marshall Tigerus
  • 3,265
  • 7
  • 32
  • 60