Let's say I have a piece of code that takes user input and stores it in integer. Now when user enters something else, the NumberFormat
exception is thrown. But since I know this may happen, but there is no reason for me to do anything about it besides checking it and then re-run the input sequence, would it be terrible idea to put the try-catch
inside do-while
loop and making a boolean a control variable? Is there a case where such exception handling could backfire at me?
Pseudo-code:
Scanner scanner = new Scanner(System.in);
boolean inputMismatch;
int number;
do {
try {
System.out.println("Enter a number");
number = Integer.parseInt(scanner.nextLine());
inputMismatch = false;
} catch (NumberFormatException e) {
e.printStackTrace();
inputMismatch = true;
}
} while (inputMismatch);