Does it make sense to do “try-finally” without “catch”?

后端 未结 6 1566
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-30 03:42

I saw some code like this:

    try
    {
        db.store(mydata);
    }
    finally
    {
        db.cleanup();
    }

I thought try

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-30 04:07

    Why does this code do it this way?

    Because apparently the code doesn’t know how to handle exceptions at this level. That’s fine – as long as one of the callers does, i.e. as long as the exception gets ultimately handled somewhere.

    Often, low-level code cannot react appropriately to exceptions because the user needs to be notified, or the exception must be logged, or another strategy has to be tried. Low-level code performs one function only and doesn’t know about higher-level decision making.

    But the code still needs to clean up its resources (because if it doesn’t, they would leak), so it does just that in the finally clause, making sure that it always happens, whether an exception was thrown or not.

提交回复
热议问题