0

I'm a beginner in java, and I've been wondering about this. Is there any way to make the code loop back if it caught an exception? For example, in this code, can I make it so that it loops back and makes the user put in input again if there was an error?

double divide = 0;
try {
    divide = sc.nextDouble();
    }
    catch (Exception e) {
    System.out.println("Please enter an actual number.");
    }
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • 3
    You shouldn't use exceptions for validating user input. Better to use a `while` loop to keep prompting for valid input. – jsheeran Nov 13 '17 at 11:55
  • In short: `break;` after `divide = sc.nextDouble;`, set the whole `try-catch` in an endless loop. – Turing85 Nov 13 '17 at 11:56
  • I'm not sure if I'm doing something wrong, but whenever I put break; in the try block and put the whole thing in an endless loop, it just starts printing out the error statement infinitely, not even giving another chance for user input. – Daniel Park Nov 13 '17 at 12:05

0 Answers0