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();
Why would this cause an IO exception?
My second question is why eclipse doesn't complain about the following code:
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. Thanks for the help in advance
Both code examples should have compiler errors complaining about an unhandled IOException. Eclipse shows these as errors in both code examples for me.
The reason is that the
close
method throws anIOException
, a checked exception, when called in thefinally
block, which is outside atry
block.The fix is to use a try-with-resources statement, which is available in Java 1.7+. The resources declared are implicitly closed.
Prior to Java 1.7, you need to wrap the calls to
close()
in their own try-catch blocks inside thefinally
block. It's a lot of verbose code to ensure that everything is closed and cleaned up.