簡體   English   中英

在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

當我取出原始聲明時,出現無法解析的符號錯誤。 當我保留它時,我得到一個已經聲明錯誤的變量。

構造此結構以在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM