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

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

    This is useful if you want the currently executing method to still throw the exception while allowing resources to be cleaned up appropriately. Below is a concrete example of handling the exception from a calling method.

    public void yourOtherMethod() {
        try {
            yourMethod();
        } catch (YourException ex) {
            // handle exception
        }
    }    
    
    public void yourMethod() throws YourException {
        try {
            db.store(mydata);
        } finally {
            db.cleanup();
        }
    }
    

提交回复
热议问题