2016-11-23 59 views
0

我試圖在打開方法中的文件時第一次使用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 ""; 
    } 
} 
+2

你寫的代碼不能拋出除FileNotFoundException之外的IOException,所以不能有任何異常來捕獲該塊。 –

+0

您可能想要使用[try-with-resources](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)以絕對確保沒有得到異常關閉掃描儀的方式。 – 4castle

+0

好的,所以回報是正確的嗎?我只需要擺脫IOException?並且試用資源會確保在最後關閉文件? –

回答

4

沒有趕上點的IOException編譯器是絕對正確的。第二個catch子句無法訪問,因爲您的代碼無法拋出除FileNotFoundException之外的IOException

把代碼的第二部分放在哪裏並不重要。我更喜歡把它放在catch子句中。

而且您不需要在catch子句中添加return語句,但可以在返回類似錯誤代碼的情況下執行此操作。我只是在方法的末尾放了一個返回值

0

因爲這會從你的try塊拋出的最高例外是FileNotFoundException所以後FileNotFoundException

相關問題