is it good to use try-finally just to make sure that something is performed when method finished?

c#

Solution

I would suggest refactoring the code within the `try` block into a new method:

data = CreateList();

...

private List<X> CreateList()
{
    List<X> list = new List<X>();
    // It's fine to return list from any point here...
}

Problem

My method returns in many points. I construct newData during execution also in many points. Regardless of where I return I need to save and store constructed result. Not to miss "return" I just surrounded the code with try-finally block so now I'm sure that newData will be stored. ``` List<X> newData = new List<X>(); try { .... update newData ..... return; ..... .... update newData .... update newData return; ..... return; } finally { // copy newData to data } ``` But I don't catch any exceptions and this code is not intended to work with exceptions. Is it acceptable in general or you can suggest another better approach?

Original source