[英]Using variable outside of try catch block (Java)
我在try catch块之前有一个已声明的变量,以确保可以在块外部访问它
/*
Try to get a list of all files.
*/
List<String> result;
try( Stream<Path> walk = Files.walk(Paths.get("data"))){
List<String> result = walk.filter(Files::isRegularFile)
.map(x -> x.toString()).collect(Collectors.toList());
}
catch(Exception e){
e.printStackTrace();
List<String> result = null;
}
ListIterator iter = result.listiterator() // cannot resolve symbol
当我取出原始声明时,出现无法解析的符号错误。 当我保留它时,我得到一个已经声明错误的变量。
构造此结构以在tryexcept子句之外使用变量的最佳方法是什么?
要解决编译错误,请仅在try-catch块之前声明result
变量:
List<String> result;
try( Stream<Path> walk = Files.walk(Paths.get("data"))){
result = walk.filter(Files::isRegularFile)
.map(x -> x.toString()).collect(Collectors.toList());
}
catch(Exception e){
e.printStackTrace();
result = null;
}
但是,请注意,在try-catch块(您的result.listiterator()
语句)之后访问result
变量而不检查其是否不为null可能会引发NullPointerException
。
您应该问自己,为什么要捕获任何异常并期望一切正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.