-1

I create a variable called "file_name" in both legs of a try-catch block -- so, it should be available whether an error is thrown or not.

But alas, when I try to use the "file_name" variable in my next try-catch block, I get "cannot find symbol".

package timelogger;

import java.io.IOException;

public class TimeLogger {

    public static void main(String[] args) throws IOException {
        try {
            String file_name = args[0];
        }
        catch (IndexOutOfBoundsException e){
            String file_name = "KL_Entries.txt";
        }

        try {
            ReadFile file = new ReadFile(file_name);
            String[] aryLines = file.OpenFile();

            int i;
            for ( i=1; i < aryLines.length - 2; i++ ) { //-2 because last two lines not entries
                //System.out.println( aryLines[ i ] ) ;

            }
            System.out.println(aryLines[1].charAt(24));
            System.out.println(aryLines[1].charAt(48));
        }

        catch (IOException e){
            System.out.println(e.getMessage());
        }
    }
}

I tried doing "public String file_name = ..." instead, but that gave error "illegal start of expression" or something.

How do I make this code compile? I feel like I'm missing something silly.

EDIT: Found this, indicating that variables are local to try-catch blocks. So, fixed the problem by declaring the variable outside the try-catch and then giving it values in the try-catch block.

Community
  • 1
  • 1
DJG
  • 485
  • 2
  • 19
  • 3
    declare your `file_name` outside of the first try/catch but initialize it like you are currently doing. – gonzo Nov 19 '15 at 21:24

2 Answers2

1

Variables declared in try-catch blocks are local to those blocks. So, declare the variable outside the try-catch, then assign it values in the try-catch.

Problem with "scopes" of variables in try catch blocks in Java

Community
  • 1
  • 1
DJG
  • 485
  • 2
  • 19
0

You have tried to define a variable file_name in the try block and the catch block. This however means that this variable is only available within that block.

What you want to do instead is define it outside. As you provide a fallback in the catch block you can define that as default and override it with the argument. Therefore you do not need a try catch anymore:

String file_name = "KL_Entries.txt";
if (args.length > 0) {
      file_name = args[0];
}
hotzst
  • 7,238
  • 9
  • 41
  • 64