Saidul Amin Nobin Saidul Amin Nobin - 2 months ago 10
Java Question

How to retry a method after an exception in java?

I am creating a program that takes input from the user.Now I want to re-run the input option if a user enters an invalid command. Like here only integer input are preferred but if the user inputs text, then I want to catch the exception and rerun the method.

I have tried this but it turns me into an infinite loop.What would be the best way to achieve this. It would be great if someone helps me on this.

boolean retry = true;

while(retry){

try{
//considering response from the user
System.out.print("\nEnter Your Command : ");
f_continue = processresponse(scanner.nextInt());
retry = false;
}catch(InputMismatchException e){

System.err.println("\nPlease Input a Valid Command from 1-5 or 0 for Exit");




}

}

Answer

If you enter something other than an integer, nextInt() will throw an exception, and what was entered will still be in the input buffer, so the next time you call nextInt(), you will read the same bad input. You should first call hasNextInt() to see if the input is an integer; if not, just call nextLine() to skip the bad input (and write a message telling the user to re-try).

Or you can just call scanner.nextLine() in the catch block.

Comments