Francisco Rios Francisco Rios - 14 days ago 8
Java Question

Why does the compiler say there is an uncreachable catch block?

I'm trying to use a try block for the first time while opening a file in a method. I use a scanner to read the words in the file into an ArrayList, and then I return a random word from this list. The problem is, when I compile, the compiler says that there is an unreachable catch block. I'm unsure if this is caused by the code itself, or if it's caused by where I put my return statements. Do I put the code that opens the file in the try block and leave the code that returns the randomly selected string after the catch blocks? Or do I put both the file code and the code that returns the string in the try block?

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 "";
}
}

Answer

The compiler is absolutely right. The second catch clause is unreachable because your code can't throw an IOException other than FileNotFoundException.

It is not really relevant where you put the second part of your code. I prefer putting it in the catch clause.

And you don't need to put a return statement in the catch clause but you can when it returns something like an error code. I would have just put a return at the end of the method