我有这个奇怪的行为与try catch块。当我初始化它里面的变量他们似乎是超出范围的,即使我之外声明它们下面的代码..尝试捕获块变量超出范围
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyFile {
public static void main(String[] args) {
FileInputStream fis;
FileOutputStream fos;
args[0] = "somefile.txt";
args[1] = "copyithere.txt";
int i;
try {
try {
fis = new FileInputStream(args[0]);
} catch (FileNotFoundException e) {
System.out.println("Input file not found");
e.getMessage();
}
try {
fos = new FileOutputStream(args[1]);
} catch (FileNotFoundException e) {
System.out.println("Output file not found");
e.printStackTrace();
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Give input and output file name");
e.getStackTrace();
}
try {
do {
i = fis.read();
fos.write(i);
} while (i != -1);
} catch (IOException e) {
System.out.println("Some IO exception");
e.getMessage();
}
}
}
奇怪的是,当我宣布变量设置为null“的FileInputStream FIS = NULL;然后这一切都变好了..不是没有初始化相当于初始化为空的声明..? 摆脱“范围错误”的另一种方式是当我把“返回;”在catch块的末尾..不应该代码运行良好吗?我可以看到这可能会导致错误,但它如何与“fis和fio的范围外错误”相关联?
确定我看到..感谢..所以在这种情况下,当我把delarations出来的该方法,并使其静态它也可以工作..你知道这个区别是什么原因吗? – Tummomoxie
更新了答案,你可以看看 – developer
你总是需要初始化你的局部变量 – developer