1

I have a variable that I have delared before a try catch block to make sure I can access it outside of the block

/*
        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

when I take the original declaration out, I get a cannot resolve symbol error. When I keep it in I get a variable already declared error.

What would be the best way to structure this to use the variable outside of the try except clause?

bell_pepper
  • 187
  • 11
  • Jist remove the declaration in the try block, only assign it to the already declared variable: `try(...){ result = ...` – NeplatnyUdaj May 22 '19 at 11:08
  • replace `List result` with `result` in the try catch – Lino May 22 '19 at 11:14
  • See also https://stackoverflow.com/questions/32805813/what-is-the-scope-of-a-variable-defined-inside-java-try-block-why-it-is-not-acc – Raedwald May 22 '19 at 11:47

1 Answers1

0

To resolve the compilation error, declare the result variable only before the try-catch block:

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

However, note that accessing the result variable after the try-catch block (your result.listiterator() statement) without checking that it's not null may throw a NullPointerException.

You should be asking yourself why you are catching any exception and expecting everything to work fine.

Eran
  • 387,369
  • 54
  • 702
  • 768