【发布时间】:2014-10-31 06:40:30
【问题描述】:
我正在编写一段代码,它会返回一个扫描器以获取用户输入的文件名。代码如下:
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对此是否视而不见,并且无论如何都需要我捕获异常?
【问题讨论】:
标签: java try-catch filenotfoundexception