Oleg Vazhnev
Oleg Vazhnev

Reputation: 24067

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

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?

Upvotes: 5

Views: 127

Answers (2)

TehBoyan
TehBoyan

Reputation: 6890

The usage of finally is intended as a backup if something fails(think of it as a fail-safe mechanism), including atomicity etc.

Generally the whole construction of your method is wrong and you can refactor it, as getting all those returns usually means you can take up another approach to things(example using a switch as someone in the comments suggested).

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1502825

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...
}

Upvotes: 6

Related Questions