[英]Why is eclipse complaining when I try to close BufferedReader in finally block?
Here is my code: 这是我的代码:
public static String readFile()
{
BufferedReader br = null;
String line;
String dump="";
try
{
br = new BufferedReader(new FileReader("dbDumpTest.txt"));
}
catch (FileNotFoundException fnfex)
{
System.out.println(fnfex.getMessage());
System.exit(0);
}
try
{
while( (line = br.readLine()) != null)
{
dump += line + "\r\n";
}
}
catch (IOException e)
{
System.out.println(e.getMessage() + " Error reading file");
}
finally
{
br.close();
}
return dump;
So eclipse is complaining about an unhandled IO exception caused by br.close();
因此,eclipse抱怨
br.close();
导致未处理的IO异常br.close();
Why would this cause an IO exception? 为什么这会导致IO异常?
My second question is why eclipse doesn't complain about the following code: 我的第二个问题是为什么eclipse不会抱怨以下代码:
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
try{
// open input stream test.txt for reading purpose.
is = new FileInputStream("c:/test.txt");
// create new input stream reader
isr = new InputStreamReader(is);
// create new buffered reader
br = new BufferedReader(isr);
// releases any system resources associated with reader
br.close();
// creates error
br.read();
}catch(IOException e){
// IO error
System.out.println("The buffered reader is closed");
}finally{
// releases any system resources associated
if(is!=null)
is.close();
if(isr!=null)
isr.close();
if(br!=null)
br.close();
}
}
}
I'd appreciate it if you kept the explanation in Laymen's terms if possible. 如果可以的话,请以Laymen的名义保留解释,我们将不胜感激。 Thanks for the help in advance
我在这里先向您的帮助表示感谢
Both code examples should have compiler errors complaining about an unhandled IOException. 这两个代码示例都应具有抱怨未处理的IOException的编译器错误。 Eclipse shows these as errors in both code examples for me.
Eclipse在我的两个代码示例中将它们显示为错误。
The reason is that the close
method throws an IOException
, a checked exception, when called in the finally
block, which is outside a try
block. 原因是
close
方法在try
块之外的finally
块中调用时, close
方法将抛出IOException
,这是一个经过检查的异常。
The fix is to use a try-with-resources statement , which is available in Java 1.7+. 解决方法是使用try-with-resources语句 ,该语句在Java 1.7+中可用。 The resources declared are implicitly closed.
声明的资源被隐式关闭。
try (BufferedReader br = new BufferedReader(new FileReader("dbDumpTest.txt")))
{
// Your br processing code here
}
catch (IOException e)
{
// Your handling code here
}
// no finally necessary.
Prior to Java 1.7, you need to wrap the calls to close()
in their own try-catch blocks inside the finally
block. 在Java 1.7之前,您需要将对
close()
的调用包装在finally
块内自己的try-catch块中。 It's a lot of verbose code to ensure that everything is closed and cleaned up. 有很多冗长的代码可以确保所有内容都已关闭并清理。
finally
{
try{ if (is != null) is.close(); } catch (IOException ignored) {}
try{ if (isr != null) isr.close(); } catch (IOException ignored) {}
try{ if (br != null) br.close(); } catch (IOException ignored) {}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.