Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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?

like image 873
Oleg Vazhnev Avatar asked May 14 '12 12:05

Oleg Vazhnev


People also ask

When should I use finally?

Why finally Is Useful. We generally use the finally block to execute clean up code like closing connections, closing files, or freeing up threads, as it executes regardless of an exception. Note: try-with-resources can also be used to close resources instead of a finally block.

Why is it advised to make use of the try catch and finally methods?

1.3. An optional finally block gives us a chance to run the code which we want to execute EVERYTIME a try-catch block is completed – either with errors or without any error. The finally block statements are guaranteed of execution even if the we fail to handle the exception successfully in catch block.

What is the purpose of the finally clause?

The finally block in java is used to put important codes such as clean up code e.g. closing the file or closing the connection. The finally block executes whether exception rise or not and whether exception handled or not. A finally contains all the crucial statements regardless of the exception occurs or not.

Is it better to use if else or try catch?

In general, try-catch blocks are great because they will break (move to the catch statement) whenever the exception occurs. If-else blocks rely on you predicting when the error will happen. Edit: Also, catch blocks won't stop your code from halting when an error is hit.


1 Answers

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...
}
like image 200
Jon Skeet Avatar answered Nov 11 '22 23:11

Jon Skeet