Try-Catch中的变量不可用于其他Try-Catch块吗?
我在try-catch块的两个支路中创建了一个名为“file_name”的变量 - 因此,无论是否抛出错误,它都应该可用。Try-Catch中的变量不可用于其他Try-Catch块吗?
但是,唉,当我尝试在我的下一个try-catch块中使用“file_name”变量时,我得到“无法找到符号”。
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());
}
}
}
我想这样做“公共字符串FILE_NAME = ...”来代替,但是这给了错误“表达的非法启动”什么的。
如何编译此代码?我觉得我错过了一些愚蠢的东西。
编辑:找到this,表明变量是try-catch块的本地变量。因此,通过在try-catch之外声明变量并在try-catch块中赋予它的值来解决问题。
在try-catch块中声明的变量对于这些块是本地的。所以,在try-catch之外声明变量,然后在try-catch中赋值。
Problem with "scopes" of variables in try catch blocks in Java
很高兴它解决了您的问题。 :) – gonzo
如果您认为它是重复的,请投票结束。 –
您试图定义在try块可变file_name
和catch块。但是,这意味着该变量仅在该块中可用。
你想要做的就是在外面定义它。当您在catch块中提供回退时,您可以将其定义为默认值并用参数覆盖它。因此,您不需要尝试捕获了:
String file_name = "KL_Entries.txt";
if (args.length > 0) {
file_name = args[0];
}
声明您的'file_name'在第一个try/catch之外,但是像您当前正在执行的那样初始化它。 – gonzo