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

后端 未结 8 1816
生来不讨喜
生来不讨喜 2021-02-02 12:07

\"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 go

8条回答
  •  不思量自难忘°
    2021-02-02 13:06

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

提交回复
热议问题