Java 为什么代码要求捕获IOException
我正在使用try-catch编写一个程序,但代码要求用try-catch包围InputStreamReader和BufferedReader以捕获IOException或使用throws声明IOException。但是,当我使用catch-to-IOException时,为什么它要求这样做呢 代码如下:Java 为什么代码要求捕获IOException,java,exception-handling,Java,Exception Handling,我正在使用try-catch编写一个程序,但代码要求用try-catch包围InputStreamReader和BufferedReader以捕获IOException或使用throws声明IOException。但是,当我使用catch-to-IOException时,为什么它要求这样做呢 代码如下: 在finallyblockclose()中,调用也可以抛出IOException。因此编译器对此表示不满,因为IOException属于Checked Exception类型,您也应该处理这种情
在
finally
blockclose()
中,调用也可以抛出IOException
。因此编译器对此表示不满,因为IOException
属于Checked Exception
类型,您也应该处理这种情况
让我们试着处理这个问题
尝试使用资源
String name = "";
try ( InputStreamReader r = new InputStreamReader(System.in);
BufferedReader 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) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
在中尝试捕捉
块,最后
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) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
br.close();
r.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
org.apache.commons.io.IOUtils.closequilly(Closeable…)
br.close()
方法也会抛出IOException
而您没有处理它们提示:使用try with resources
。br.close()
和r.close()
都可以抛出IOException
s,最后不是try catch
代码的一部分,因此它们不会被包括在内,你必须分开处理。事实上,Java现在包含了一个为您实现这一点的功能,有关更多详细信息,请参阅。但是,如果我使用Scanner而不是BufferedReader,那么在finally bliock close()方法中,不会请求捕获IOException。为什么?
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) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
br.close();
r.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
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) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
finally {
IOUtils.closeQuietly(br, r);
}