Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I handle an IOException which I know can never be thrown, in a safe and readable manner?

Tags:

"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:

  1. The file has been checked to exist but the extremely unlikely possibility exists that through some major fault of reality the file might be deleted before this method is called.
  2. Since the probability of 1 happening is extremely unlike and unrecoverable, I would prefer to define an unchecked exception.
  3. The file is has already been found to exist, forcing other programmers to write code and catch the checked FileNotFoundException seems tedious and useless. The program should just fail completely at that point. For example there is always the chance that a computer may catch fire, but no one is insane enough to force other programmers to handle that as a checked exception.
  4. I run into this sort of Exception issue from time to time, and defining custom unchecked exceptions each time I encounter this problem (my old solution) is tiresome and adds to code-bloat.

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?

like image 437
Ethan Heilman Avatar asked Jun 25 '09 19:06

Ethan Heilman


People also ask

How do you handle IOException?

IOException is a Java exception that occurs when an IO operation fails. Develop can explicitly handle the exception in a try-catch-finally block and print out the root cause of the failure. The developer can take the correct actions to solve this situation by having additional code in the catch and finally blocks.

Which method will throw an IOException?

The Machine class has a public method called run(). This method declares that it throws an IOException. IOException (input-output exception) is part of the Java standard library.

Which of the following method does not throw IOException?

io.

What does throw IOException mean?

The throws keyword indicates that a certain method can potentially "throw" a certain exception. You need to handle a possible IOException (and possibly other exceptions) either with a try-catch block or by adding throws IOException, (...) to your method declaration.


2 Answers

You can convert a checked exception to an unchecked by nestling it inside a RuntimException. If the exception is caught higher up in the stack and outputted using printStackTrace(), the stack for the original exception will be displayed as well.

try {
    // code...
}
catch (IOException e) {
    throw new RuntimeException(e);
}

This is a good solution, that you shouldn't hesitate to use in these situations.

like image 44
Emil H Avatar answered Sep 20 '22 19:09

Emil H


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);
}
like image 97
Henning Avatar answered Sep 19 '22 19:09

Henning