When you throw an exception, the operation is just canceled usually. If you just want to ask the user to try again due to invalid input, you don't really need to worry about exceptions.
Code:
public class TestException
{
private String name = "";
public TestException(String name)
{
this.name = name;
}
public void setName(String s) throws Exception
{
if (s == null || s.equals(""))
throw new Exception("String is either null or empty");
}
public static void main(String[] args)
{
TestException test = new TestException("johnny");
try{
test.setName("");
}
catch(Exception e){
System.out.println(e);
}
}
}
The while loop will continue until the user has entered valid input.
Code:
String input = "";
while (input == null || input.equals(""))
{
//prompt user for input...
//validate input
if (input == null || input.equals(""))
System.out.println("Sorry, invalid input. Please try again.");
}
Bookmarks