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

后端 未结 8 1815
生来不讨喜
生来不讨喜 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:02

    You are probably better off throwing the superclass and more generic exception IOException at any point in your code which involves reading or writing from the file.

    The file may exist when your class's constructor runs, but that doesn't guarantee that:

    1. It exists when methods are called
    2. It's writable/readable
    3. Another thread doesn't access it and somehow screw up your streams
    4. The resource doesn't go away in the middle of processing

    etc.

    Instead of reinventing the wheel, I would say just re-throw IOException wherever the JDK/java.io classes you are using force you to do so.

    Also I for one hate classes that throw Exceptions from their constructor - I'd get rid of these if I were you.

提交回复
热议问题