如何写IOException异常处理程序
问题描述:
我想知道如果要抛出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;
}
或在该方法内。
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;
}
是否有必要包括一个自定义的消息,以防一个被引发?回到这个问题Java - What throws an IOException我无法测试会发生什么。
不知道这是否应该codereview,因为我不确定它是否会实际工作。
答
如果stdin.readLine()
抛出一个IOException,试图再次从stdin重新读取将不会成功:您将得到另一个IOException,使您的第二个片段进入一个无限递归循环,以*Error结束。
答
您可以触发IOException进行测试。只需在您的if语句添加了这个:
throw new IOException("Testing Failure");
至于如何处理异常它实际上取决于如果你想目前的方法来处理它,或者如果你只是想将它传递给任何被称为方法。
Ahhhh,回答我的另一个问题...更好的是在这里比代码审查..对不起,我厚得像两块木板,我最终会学习 –