当我尝试在finally块中关闭BufferedReader时,为什么eclipse会抱怨?

时间:2015-06-17 18:32:51

标签: java eclipse exception bufferedreader try-catch-finally

这是我的代码:

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;

所以eclipse抱怨由br.close();

引起的未处理的IO异常

为什么会导致IO异常?

我的第二个问题是为什么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();
      }
   }
}

如果你能按照Laymen的条款解释,我会很感激。感谢您的帮助

1 个答案:

答案 0 :(得分:7)

两个代码示例都应该有编译错误抱怨未处理的IOException。 Eclipse在我的两个代码示例中都将这些显示为错误。

原因是close方法在IOException块中调用时会抛出finally,这是一个已检查的异常,该块位于try块之外。

修复方法是使用Java {x}中提供的try-with-resources statement。声明的资源是隐式关闭的。

try (BufferedReader br = new BufferedReader(new FileReader("dbDumpTest.txt")))
{
   // Your br processing code here
}
catch (IOException e)
{
   // Your handling code here
}
// no finally necessary.

在Java 1.7之前,您需要在close()块内的自己的try-catch块中包含对finally的调用。这是一个冗长的代码,以确保所有内容都被关闭和清理。

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) {}
}