在 try catch 块之外使用变量 (Java)

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

当我取出原始声明时,出现无法解析符号错误。 当我保留它时,我得到一个变量已经声明的错误。

构建此结构以在 try except 子句之外使用变量的最佳方法是什么?

要解决编译错误,请仅在 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

您应该问问自己为什么要捕获任何异常并期望一切正常。