我試圖在打開方法中的文件時第一次使用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?並且試用資源會確保在最後關閉文件? –