我试图在打开方法中的文件时第一次使用try块。我使用扫描器将文件中的单词读入ArrayList,然后从该列表中返回一个随机单词。问题是,当我编译时,编译器说有一个无法访问的catch块。我不确定这是由代码本身引起的,还是由于我在哪里放置了我的返回语句。我是否将在try块中打开该文件的代码放在代码中,并在catch块之后留下随机选择的字符串返回的代码?或者我将文件代码和返回字符串的代码放在try块中?为什么编译器会说有一个不可删除的catch块?
public String loadPuzzle() {
try {
ArrayList<String> puzzles = new ArrayList<String>();
Scanner sc = new Scanner(new File("Categories.txt"));
while (sc.hasNext()) {
String line = sc.nextLine();
puzzles.add(line);
}
sc.close();
//do i do the return statement here or after the try and catch blocks?
int r = new Random().nextInt(puzzles.size() + 1);
return puzzles.get(r);
}
catch(FileNotFoundException e) {
System.out.println("The file was not found.");
return "";
// do i need to return a value in the catch blocks?
}
//the compiler throws the warning here: unreachable catch clause and FileNotFoundException already found
catch(IOException e) {
System.out.println(e);
return "";
}
}
你写的代码不能抛出除FileNotFoundException之外的IOException,所以不能有任何异常来捕获该块。 –
您可能想要使用[try-with-resources](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)以绝对确保没有得到异常关闭扫描仪的方式。 – 4castle
好的,所以回报是正确的吗?我只需要摆脱IOException?并且试用资源会确保在最后关闭文件? –