【发布时间】:2018-09-08 08:07:23
【问题描述】:
我正在使用 try catch 编写程序,但代码要求使用 try-catch 包围 InputStreamReader 和 BufferedReader 以捕获 IOException 或使用 throws 声明 IOException。但是为什么当我对 IOException 使用 catch 时它会要求这样做。
代码如下:
public class BufferedReader3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
InputStreamReader r=null;
BufferedReader br=null;
String name="";
try
{
r =new InputStreamReader(System.in);
br =new BufferedReader(r);
while(!name.equals("stop"))
{
System.out.println("Enter data: ");
name=br.readLine();
}
System.out.println("data is: "+name);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
br.close();
r.close();
}
}
}
【问题讨论】:
-
.close()方法也会抛出IOException而你没有处理它们 -
提示:使用
try-with-resources。 -
br.close()和r.close()都可以抛出IOExceptions,finally不是代码的try-catch部分的一部分,因此它们不会被包含在内,您必须分别处理。事实上,Java 现在包含一项功能可以为您执行此操作,请参阅The try-with-resources Statement 了解更多详情