我有这两种方法从文件中读取多个整数并将它们插入树中。如果找到该文件,它可以正常工作,但如果找不到该文件,则不会打印“找不到文件”。为什么不进入catch语句?谢谢!
public static void openF(Tree myT)
{
try
{
x=new Scanner(new File("Number.txt"));
readF(myT);
}
catch(Exception e)
{
System.out.println("File not found");
}
}
// to read from the file
public static void readF(Tree myT)
{
while(x.hasNext()) //keeps going till it reaches the end of file
{
int a =x.nextInt();
myT.insert(a); //insert in tree
}
}
答案 0 :(得分:2)
我测试了代码的简化版本:
public static void main(String[] args) {
try {
new Scanner(new File("H:\\Hello.txt"));
System.out.println("The file exists.");
} catch (Exception e) {
System.out.println("File not found: " + e.getMessage());
}
}
文件存在时,会打印The file exists.
。如果没有,则打印File not found: H:\Hello.txt (The system cannot find the file specified)
。
所以不,catch块按预期运行。错误在您的代码中的其他位置,但鉴于您没有提供完整代码,也没有提供实际编译的部分(x
未声明),我们无法猜测实际错误的位置是