"The major difference between a thing that might go wrong and a thing that cannot possibly go wrong is that when a thing that cannot possibly go wrong goes wrong it usually turns out to be impossible to get at or repair." -Douglas Adams
I have an class FileItems. FileItems constructor takes a file, and throws an exception (FileNotFoundException) if the file doesn't exist. Other methods of that class also involve file operations and thus have the ability throw the FileNotFoundException. I would like to find a better solution. A solution which doesn't require that other programmers handle all of these extremely unlikely FileNotFoundExceptions.
The facts of the matter:
The code currently looks like this
public Iterator getFileItemsIterator() {
try{
Scanner sc = new Scanner(this.fileWhichIsKnowToExist);
return new specialFileItemsIterator(sc);
} catch (FileNotFoundException e){ //can never happen}
return null;
}
How can I do this better, without defining a custom unchecked FileNotFoundException? Is there some way to cast a checkedException to an uncheckException?
The usual pattern to deal with this is exception chaining. You just wrap the FileNotFoundException in a RuntimeException:
catch(FileNotFoundException e) {
throw new RuntimeException(e);
}
This pattern is not only applicable when an Exception cannot occur in the specific situation (such as yours), but also when you have no means or intention to really handle the exception (such as a database link failure).
Edit: Beware of this similar-looking anti-pattern, which I have seen in the wild far too often:
catch(FileNotFoundException e) {
throw new RuntimeException(e.getMessage());
}
By doing this, you throw away all the important information in the original stacktrace, which will often make problems difficult to track down.
Another edit: As Thorbjørn Ravn Andersen correctly points out in his response, it doesn't hurt to state why you're chaining the exception, either in a comment or, even better, as the exception message:
catch(FileNotFoundException e) {
throw new RuntimeException(
"This should never happen, I know this file exists", e);
}