Reputation:
I am wondering if the first way to throw an IOException is the better way to do this,
Like this , but I can't trigger an IOException to test it.
public static String inputStr (String prompt) throws IOException
{
String inputStr = "";
System.out.print(prompt);
inputStr = stdin.readLine();
if (inputStr.length() == 0)
{
System.out.println("Error! Enter valid field!");
inputStr(prompt);
}
return inputStr;
}
Or within the method.
public static String inputStr (String prompt)
{
String inputStr = "";
System.out.print(prompt);
try
{
inputStr = stdin.readLine();
if (inputStr.length() == 0)
{
System.out.println("Error! Enter valid field!");
inputStr(prompt);
}
} catch (IOException e)
{
System.out.println("Error! Enter valid field!");
inputStr(prompt);
}
return inputStr;
}
Is it necessary to include a customised message in case one is thrown? Re this question Java - What throws an IOException I am unable to test for what will happen.
Not sure if this should be codereview, as I am unsure if it actually will work.
Upvotes: 1
Views: 817
Reputation: 691715
If stdin.readLine()
throws an IOException, trying to re-read again from stdin won't succeed: you'll get another IOException, making your second snippet go into an infinite recursive loop, ending with a StackOverflowError.
Upvotes: 5
Reputation: 23629
You can trigger an IOException to test. Just added this in your if statement:
throw new IOException("Testing Failure");
As far as how you deal with the exception it really depends on if you want the current method to deal with it or if you just want to pass it to whatever called the method.
Upvotes: 3