Is it useful to use try-finally to make sure that something is executed when finished?

My method returns at many points. In many cases, I create newData at runtime. No matter where I return, I need to save and keep the result built. In order not to miss the “return”, I just surrounded the code with a try-finally block, so now I’m sure that newData will be saved.

List<X> newData = new List<X>();
try
{
    ....
    update newData
    .....
    return;
    .....
    ....
    update newData
    ....
    update newData
    return;
    .....
    return;
} finally
{
    // copy newData to data    
}

But I do not understand any exceptions, and this code is not intended to work with exceptions. Is this acceptable overall or can you suggest another better approach?

+5
source share
2 answers

I would suggest refactoring the code in a block tryinto a new method:

data = CreateList();

...

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

, , , - ( ), ..

, , , , (, , - ).

+2

All Articles