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

后端 未结 6 1679
爱一瞬间的悲伤
爱一瞬间的悲伤 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:02

    The finally block ensures that even when a RuntimeException is thrown (maybe due to some bug in the called code), the db.cleanup() call will be made.

    This is also often used to prevent too much nesting:

    try
    {
        if (foo) return false;
        //bla ...
        return true;
    }
    finally
    {
        //clean up
    }
    

    Especially when there are many points at which the method returns, this improves readability as anyone can see the clean up code is called in every case.

提交回复
热议问题