【问题标题】:Try-Catch-Finally - Final Block not recognising variableTry-Catch-Finally - 最终块无法识别变量
【发布时间】:2014-08-09 04:32:13
【问题描述】:

首先我知道我应该对资源使用 try-catch,但是目前我的系统上没有最新的 JDK。

我有下面的代码,并试图确保资源 reader 使用 finally 块关闭,但是下面的代码由于两个原因无法编译。首先是 reader 可能尚未初始化,其次 close() 应该在它自己的 try-catch 中被捕获。这两个原因都不会破坏初始 try-catch 块的对象吗?

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

我假设我在某个地方出错了?感谢您的帮助!

干杯,

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;
    }

【问题讨论】:

    标签: java try-catch-finally


    【解决方案1】:

    没有其他方法可以初始化缓冲区并捕获异常。编译器永远是对的。

    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-block,因为它声明它可以抛出一个IOException。调用是在 finally 块中还是在其他地方都没有关系。它只是需要处理。这是一个检查异常。

    Read 也必须由 null 初始化。恕我直言,这是超级没用的,但那是 Java。这就是它的工作原理。

    【讨论】:

    • Excatly,似乎毫无意义的代码生成:S 感谢您帮助解决初始化问题。
    【解决方案2】:

    而是检查reader 是否为空,然后像下面这样相应地关闭它(你应该在reader 上调用close(),只有当它不为空或者它已经被实例化时,否则你最终会得到@987654324 @异常)。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-13
      • 2011-02-20
      • 2013-12-16
      • 2011-06-01
      • 2015-09-05
      • 2018-10-03
      • 2015-10-27
      • 2014-11-27
      相关资源
      最近更新 更多