[英]Try-Catch-Finally - Final Block not recognising variable
首先,我知道我应该使用带有资源的try-catch,但是目前我的系统上没有最新的JDK。
我在下面有以下代码,并试图确保使用finally块关闭资源读取器 ,但是以下代码由于两个原因而无法编译。 首先是读者可能尚未初始化,其次应该在自己的try-catch中捕获close()。 这两个原因都不能击败最初的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;
}
没有其他方法可以初始化缓冲区并捕获异常。 编译器总是正确的。
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块中还是其他地方都没有关系。 它只需要处理。 这是一个检查的异常。
读取还必须仅由null初始化。 恕我直言,这是超级没用的,但这就是Java。 这就是它的工作方式。
相反,请检查reader
是否为null,然后按如下所示将其相应close()
仅当reader
不为null或已被实例化时,才应在reader
上调用close()
,否则最终将得到null reference
异常)。
finally
{
if(reader != null)
{
reader.close();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.