2014-05-07 40 views
0

我只是回顾一下我们在一个java类中编写的代码,我注意到在finally块中有一个关闭阅读器的try/catch,但不是作者。我会复制下面的代码。任何人都可以解释为什么会这样吗?我想更好地理解。关闭阅读器和写入器的异常处理

public class UsingFiles { 
public static void main(String[] args) { 
    // open the input stream (from the file of this program) 
    BufferedReader reader = null; 
    PrintWriter writer = null; 
    try { 
     reader = new BufferedReader(new FileReader("./src/UsingFiles.java")); 
     writer = new PrintWriter("reverseFile.txt"); 
     // String line; 
     // while ((line = reader.readLine()) != null) { 
     // System.out.println(line); 
     // } 
     // print the file in reverse order 
     // use recursion 
     reverseFile(reader, writer); 
    } catch (FileNotFoundException e) { 
     System.out.println("Couldn't open the file!"); 
    } catch (IOException e) { 
     System.out.println("Problem reading the file"); 
    } finally { 
     if (reader != null) { 
      try { 
       reader.close(); 
      } catch (IOException e) { 
       System.out.println("Couldn't close the reader"); 
      } 
     } 
     if (writer != null) { 
      writer.close(); 
     } 
    } 
} 

private static void reverseFile(BufferedReader reader, PrintWriter writer) 
     throws IOException { 
    String line = reader.readLine(); 
    if (line != null) { 
     reverseFile(reader, writer); 
     writer.println(line); 
    } 
} 

回答

3

有迹象表明,我能想到的两种可能性:

  1. 这是一个疏忽
  2. close()两个调用可以抛出异常。如果第一个抛出异常,第二个将被跳过 - 除非第一个被封装在自己的try/catch块中。因为如果失败的话,有可能会被跳过

在“现实世界”没有后续的代码的第二个不需要try/catch块,我要说的是,答案是#1。我认为#2不太可能的原因是通常会有一些其他的代码需要执行,即使您无法关闭某些流。如果catch块没有发现异常(或重新抛出一个不同的异常),那么情况尤其如此,因为finally块中的新异常将替换原始异常,并且您永远不会知道它发生了。

更新

作为另一个答案指出,PrintWriter.close()其实并没有抛出IOException,即使父接口Writer不声明close()可以抛出IOException。所以这可能是一个更好的解释。

0

没有必要关闭读者try块的finally块,如果你使用的是尝试与资源

try(reader = new BufferedReader(new FileReader("./src/UsingFiles.java")) 
{ 

} 

catch(Exception e) 
{ 
} 
1

相信意图是试图关闭即使读者无法关闭作家。如果关闭读取器会抛出一个IOException,那么您将永远不会执行finally块的其余部分。

1

这是因为PrintWriter在close()期间从不抛出异常。请参阅API。这

  try { 
       writer.close(); 
      } catch(IOException e) { 
       System.out.println("Couldn't close the writer"); 
      } 

将导致编译器错误:IOException的无法访问catch块。这个例外不会从try语句主体