Yve*_*omb 1 java error-handling try-catch ioexception
我想知道抛出IOException的第一种方法是更好的方法,
像这样,但我无法触发IOException来测试它.
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;
}
Run Code Online (Sandbox Code Playgroud)
或者在方法内.
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;
}
Run Code Online (Sandbox Code Playgroud)
是否需要包含自定义消息以防万一被抛出?重新提出这个问题Java - 什么抛出IOException我无法测试会发生什么.
不确定这应该是codereview,因为我不确定它是否真的可行.
如果stdin.readLine()抛出IOException,尝试从stdin重新读取将不会成功:您将获得另一个IOException,使您的第二个片段进入无限递归循环,以StackOverflowError结束.