2014-06-18 9 views
0

首先,我知道我应该使用带资源的try-catch,但是我目前没有在我的系统上使用最新的JDK。Try-Catch-Finally - Final Block无法识别变量

我有下面的代码,并试图确保资源阅读器关闭使用finally块,但下面的代码不能编译的原因有两个。首先,读者可能还没有被初始化,其次close()应该在自己的try-catch中被捕获。这两个原因都不是击败了初始try-catch块的对象吗?

我可以通过将它放在自己的try-catch中来解决finally块close()语句的问题。然而这还留下关于读者未被初始化的编译错误?

我假设我出事了吗?帮助赞赏!

干杯,

public Path [] getPaths() 
    { 
     // Create and initialise ArrayList for paths to be stored in when read 
     // from file. 
     ArrayList<Path> pathList = new ArrayList(); 
     BufferedReader reader; 
     try 
     { 
      // Create new buffered read to read lines from file 
      reader = Files.newBufferedReader(importPathFile); 
      String line = null; 
      int i = 0; 
      // for each line from the file, add to the array list 
      while((line = reader.readLine()) != null) 
      { 
       pathList.add(0, Paths.get(line)); 
       i++; 
      } 
     } 
     catch(IOException e) 
     { 
      System.out.println("exception: " + e.getMessage()); 
     } 
     finally 
     { 
      reader.close(); 
     } 


     // Move contents from ArrayList into Path [] and return function. 
     Path pathArray [] = new Path[(pathList.size())]; 
     for(int i = 0; i < pathList.size(); i++) 
     { 
      pathArray[i] = Paths.get(pathList.get(i).toString()); 
     } 
     return pathArray; 
    } 

回答

2

没有其他方式,然后初始化您的缓冲区并捕获异常。编译器总是正确的。

BufferedReader reader = null; 
try { 
    // do stuff 
} catch(IOException e) { 
    // handle 
} finally { 
    if(reader != null) { 
     try { 
      reader.close(); 
     } catch(IOException e1) { 
      // handle or forget about it 
     } 
    } 
} 

方法close永远需要一个try-catch块,因为它宣称,它可以抛出IOException。如果调用位于finally块或其他位置,则无关紧要。它只是需要处理。这是一个检查的例外。

阅读也必须初始化为null。恕我直言,这是超级无用的,但这是Java。这就是它的工作原理。

+0

Excatly,看起来像无意义的代码生成:S感谢帮助解决初始化问题。 – Dave0504

0

相反检查reader为空或不是,然后相应地关闭它像下面(你应该叫close()reader只有当它不为空,或者如果它已经早已其他实例,你将结束后来得到null reference例外)。

finally 
    { 
     if(reader != null) 
     { 
      reader.close(); 
     } 
    } 
+0

感谢您的输入Rahul – Dave0504