2016-11-23 57 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

相关问题