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

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

    Don't just tank your entire application with a RuntimeException when you encounter an unlikely error condition. RuntimeException should be reserved for programmer errors, and IOException is most likely not caused by programmer error.

    Instead, encapsulate the lower level exception in a higher level exception and rethrow. Then handle the higher level exception up the call chain.

    For example:

    class SomeClass {
    
      public void doActions() {
        try {
          someAction();
        } catch (HigherLevelException e) {
          notifyUser();
        }
    
        someOtherUnrelatedAction();
      }
    
      public void someAction() throws HigherLevelException {  
        try {
          // user lower-level abstraction to do our bidding
        } catch(LowerLevelException e) {
          throw new HigherLevelException(e);
        }
      }
    
      public void someOtherUnrelatedAction() {
        // does stuff
      }
    }
    

    Most likely the call stack that threw the exception was performing some task in your application. Instead of force crashing your entire application with a RuntimeException figure out what to do when the problem occurs during that task. For example, were you trying to save a file? Don't crash, instead notify the user there was an issue.

提交回复
热议问题