我对 try catch block 有这种奇怪的行为。当我初始化其中的变量时,即使我在外部声明它们,它们似乎超出了以下代码的范围..
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; 然后一切都会好起来.. 没有初始化的声明不等于初始化为 null..? 摆脱“超出范围错误”的另一种方法是当我输入“return;”时在 catch block 的末尾......代码不应该在没有它的情况下正常运行吗?我可以看到这可能会导致错误,但这与“fis 和 fio 超出范围错误”有何联系?
最佳答案
isn't declaration without initialization equivalent to initialization to null..?
不适用于局部变量。创建实例时仅初始化实例变量。
The other way which gets rid off "out of scope error" is when I put "return;"
您应该使用 Java 7 中引入的 try with resources
block 。它将自动关闭流,例如:
int i;
try(FileInputStream fis = new FileInputStream(args[0]);
FileOutputStream fos = new FileOutputStream(args[1]);){
do {
i = fis.read();
fos.write(i);
} while (i != -1);
}
关于java - 尝试 catch block 变量超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43057248/