关于try/catch和访问try中的元素的java帮助
try {
inFile = new Scanner(file);
}
catch (FileNotFoundException e) {
System.out.println("FileNotFoundException");
}
我有这个密码。但是,在try/catch语句之后,我有以下内容:
while(inFile.hasNext()) {
}
编译器告诉我我还没有初始化infle。我是否需要将所有代码都放在try/catch中?我做错了什么
# 1 楼答案
是的,你知道。如果引发异常,运行时将打印“FileNotFoundException”,并将继续运行,尽管尚未初始化内嵌
当遇到此异常时,您应该使程序返回,或者仅当您确定程序已正确初始化时,才对
infile
执行操作# 2 楼答案
如果遇到编译器错误,可能需要将
inFile
初始化为null请注意,在以后的代码中,您不应该假设infle不是null,您应该始终检查它:
例如
# 3 楼答案
编译器正在抱怨,因为如果
new Scanner()
抛出FileNotFoundException
,inFile
将无法初始化(顺便说一句,非常不幸的变量名)。循环应该位于try
块内,这也将增加可读性# 4 楼答案
try块与while循环不在同一范围内。将while循环放在try块中
# 5 楼答案
初始化填充:
编辑:
正如其他人所提到的,您应该小心,您可能会在while循环中获得NullPointerException。您应该考虑将while循环移动到TIE块中:
# 6 楼答案
出现警告的原因是,您应该首先将扫描仪设置为null。但是,您还应该将while循环移动到try块中,因为如果抛出异常,您不希望执行该while循环(因为infle将为null)