Is finally block really necessary for the clean up code (like closing streams)?

前端 未结 8 2199
情歌与酒
情歌与酒 2021-02-15 10:14

I am very confused as to why do I need to need to put the clean-up code like closing streams in a finally block.

I\'ve read that the code in finally<

相关标签:
8条回答
  • 2021-02-15 11:08

    If an Exception occurs, ie, the try block is executed, then, rest assured, the finally block will also be executed. It's just a safeguard option instead of putting an unreliable assumption that the rest of the method will get executed.

    0 讨论(0)
  • 2021-02-15 11:09

    Maybe there is a slight misunderstanding here (or this is myself who misunderstand). The finally block is run whether a method exits on exceptional conditions or not, e.g.

     try {
          throw new Exception();
     }
     finally {
          // Block of code will be called before the method exits as exception is thrown
     }
    

    Note that there is (very) few exception to this rule, as, for instance:

     try {
          System.exit(-1);
     }
     finally {
          // Block of code will be called before the method exits as exception is thrown
     }
    

    This is a (quite dangerous) case where the program will exit without executing the finally block.

    0 讨论(0)
提交回复
热议问题