I am trying to loop a try block every time an exception is thrown.
An example might be when the program prompts for a double and the user enters a string, so, a NumberFormatException is thrown. So the program will request the user to re-enter.
Here’s what I am doing currently. Is this the proper way to do so or is there better way?
// infinite loop
for (;;)
{
try
{
//do something
break; // if an exception is not thrown. it breaks the loop.
}
catch (Exception e)
{
//display the stack trace.
}
// restarts the for loop
}
Instead of throwing exceptions according to the input, keep your restrictions on the user input by getting use of the regular expressions. Java regular expressions will help you at this point.