我在写一段代码,它返回用户输入文件名的扫描器。下面的代码:FileNotFoundException不被抛出
public static Scanner getInputScanner(Scanner console) {
System.out.print("Enter input file: ");
String fileName = "";
try {
fileName = console.nextLine();
File f = new File(fileName);
} catch (FileNotFoundException e) {
while (!(new File(fileName)).exists()) {
System.out.println(fileName + " (No such file or directory)");
System.out.print("Enter input file: ");
fileName = console.nextLine();
}
}
File f = new File(fileName);
return new Scanner(f);
}
我得到两个错误:
Compression.java:49: error: exception FileNotFoundException is never thrown in body of corresponding try statement
} catch (FileNotFoundException e) {
^
Compression.java:57: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
return new Scanner(f);
我想不通为什么try块不是抛出一个异常,因为用户可以输入无效的文件名。
感谢您的任何帮助。
编辑:将FileNotFoundException更改为NullPointerException并解决第一个问题。但是,现在我得到一个错误,我的return语句抛出一个未报告的FileNotFoundException。但是这个代码不会执行,除非该文件是有效的,对吧? Java对此是否是盲目的,并且要求我捕捉异常呢?