我觉得它更容易只显示代码,我变得比去解释它:)在Java中,为什么在尝试显示FileNotFoundException时收到NullPointerException?
这是我的主要方法的输出:
//prompt user for filename
System.out.println("Please enter the text file name. (Example: file.txt):");
String filename = ""; //will be used to hold filename
//loop until user enters valid file name
valid = false;
while(!valid)
{
filename = in.next();
try
{
reader.checkIfValid(filename);
valid = true; //file exists and contains text
}
catch (Exception e)
{
System.out.println(e + "\nPlease try again.");
}
}
这是reader.checkIfValid方法:
public void checkIfValid(String filename) throws InvalidFileException, FileNotFoundException
{
try
{
in = new Scanner(new File(filename));
if (!in.hasNextLine()) // can't read first line
throw new InvalidFileException("File contains no readable text.");
}
finally
{
in.close();
}
}
这是输出当输入一个不存在的文件,我得到:
请输入文本文件名。 (例如:file.txt的):
doesNotExist.txt
显示java.lang.NullPointerException
请重试。
为什么System.out.println(e)得到NullPointerException?当我输入一个空文件或文本文件时,它工作得很好。空文件打印InvalidFileException(自定义异常)消息。
当我把一个try-catch语句围绕“在=新的扫描仪(新文件(文件名));”,并有catch块显示异常,我做得到FileNotFoundException异常打印出来,其次通过 NullPointerException(我不完全确定为什么如果在checkIfValid方法中已经捕获异常,主方法中的catch块将被激活...)。
我在这上面花了一段时间,对于什么是错的,我完全无能为力。任何帮助,将不胜感激。谢谢!
我认为,* reader *为空。 – adatapost
可以请你发布错误stacktrace –
@sheldonCooper,我没有看到一个堆栈跟踪?我在哪里可以找到它?此外,我初始化阅读器,它只会导致这个空的异常,当文件是坏*。 – yts