javascoping

Access variable in try block


I want to remove the throws FileNotFoundException from the method head and put it into it.

public static String[] read(String file) throws FileNotFoundException {

But then I can't access in (the scanner) anymore! How to handle that?

public static String[] read(String file) {
    try {
        Scanner in = new Scanner(new FileReader(file));
    }
    catch (Exception e) {
    }
    // ...
    in.close();
    // ...
}

Solution

  • The variable in is out of scope outside the try block. You can either do this:

    public static String[] read(String file) {
        Scanner in = null;
        try {
            in = new Scanner(new FileReader(file));
        }
        catch (Exception e) {
        }
        finally() {
            in.close();
        }
        // ...
    }
    

    Or better yet, try with resources

    public static String[] read(String file) {
        try (Scanner in = new Scanner(new FileReader(file))){
            String line = in.nextLine();
            // whatever comes next
        }
        catch (Exception e) {
        }
            
        // right here, the scanner object will be already closed
        return ...;
    }