在下面的程序中,如果我删除了return语句
catch(FileNotFoundException e) {
System.out.println("File Not Found");
return;
在do while循环中显示了一个错误,局部变量fin
可能没有初始化。有人能解释一下为什么会这样吗?
import java.io.*;
class Stock {
public static void main(String args[])
throws IOException {
int i;
FileInputStream fin;
try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException e) {
System.out.println("File Not Found");
return;
}
// read characters until EOF is encountered
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);
fin.close();
}
}
如果您删除return
语句,您将得到:
public static void main(String args[])
throws IOException {
int i;
FileInputStream fin;
try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException e) {
System.out.println("File Not Found");
}
// read characters until EOF is encountered
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);
fin.close();
}
现在如果FileInputStream
抛出异常,它不会返回结果,并且fin
不会初始化。catch
块处理异常并打印一条消息,但随后代码继续,它试图执行的下一件事是i = fin.read()
。由于编译器发现有一种方法可以不初始化fin
或为其赋值而到达该语句,因此它不会编译该程序。
如果你把return
放回去,这就不会发生了,因为catch
块会导致main
返回,而你不能到达fin.read()
。
异常可以在try块的调用中抛出,因此没有值将被分配给变量fin
。如果没有return语句,后续使用未初始化的fin
变量会导致编译器报错。
对于return语句,如果fin
变量从未初始化,它也不会被使用,所以编译器可以接受。
为什么编译器会报错
- if your main() encounter the exceptions it will pass try catch block and never get the
chance to initialize fin variable
- Compiler knows that program may end up with throwing an exception which has high chance
in order to avoid any fruther issue it will not complie
我建议你这样做
- use try catch block with resources since Java 7 since Class `FileInputStream` is `closable`
- put everything in a good order
代码:try(FileInputStream fin =new FileInputStream(args[0]) ) {
while ((content = fin.read()) != -1) {
// convert to char and display it
System.out.print((char) content);
}
} catch(FileNotFoundException e) {
System.out.println("File Not Found");
return;
} ...
....
..
源:http://docs.oracle.com/javase/7/docs/api/java/io/FileInputStream.html http://tutorials.jenkov.com/java-exception-handling/try-with-resources.html new FileInputStream(args[0]);
中可能出现异常,导致fin未初始化。
尝试使用fin的默认值:
fin = null;
然后,检查它是否为空:
if (fin != null)
{
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);
fin.close();
}
如果在实例化FileInputStream时遇到异常,则在将值存储到变量fin之前将控制移到catch块。如果没有return语句,程序将继续执行到do/while循环,其中将对未初始化的变量调用方法(read),从而导致错误。