Angela
Angela

Reputation: 3389

Does code in a finally get executed if I have a return in my catch() in c#?

I have the following code snippet / example. It's not working code I just wrote this so as to ask a question about catch, finally and return:

try
{
    doSomething();
}
catch (Exception e)
{
    log(e);
    return Content("There was an exception");
}
finally
{
    Stopwatch.Stop();
}
if (vm.Detail.Any())
{
    return PartialView("QuestionDetails", vm);
}
else
{
    return Content("No records found");
}

From what I understand if there's an exception in the try block it will go to catch. However if there is a return statement in the catch then will the finally be executed? Is this the correct way to code a catch and finally ?

Upvotes: 10

Views: 3308

Answers (5)

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26737

The finally will be executed even if there is a return within the catch block

finally block is always executed

Upvotes: 4

geratri
geratri

Reputation: 111

The code in the finally block will run despite the return statement in your catch block. However, I personally would assign the result to a variable and return it after the block. But that's just a matter of taste.

Upvotes: 2

dknaack
dknaack

Reputation: 60468

Yes the finally will get executed, even if you return something before.

The finally block is useful for cleaning up any resources that are allocated in the try block, and for running any code that must execute even if an exception occurs in the try block. Typically, the statements of a finally block are executed when control leaves a try statement, whether the transfer of control occurs as a result of normal execution, of execution of a break, continue, goto, or return statement, or of propagation of an exception out of the try statement.

More Information

MSDN - try-finally (C# Reference)

Upvotes: 10

Christian.K
Christian.K

Reputation: 49260

The finally will execute after the catch-block is exited (in your by means of an explicit "return"). However, everything after the finally-block (in your case the if (vm.Detail.Any()) ...) will not execute.

Upvotes: 3

Mitch Wheat
Mitch Wheat

Reputation: 300559

Within a handled exception, the associated finally block is guaranteed to be run. However, if the exception is unhandled, execution of the finally block is dependent on how the exception unwind operation is triggered. That, in turn, is dependent on how your computer is set up. For more information, see Unhandled Exception Processing in the CLR.

Ref: Try-Finally

Upvotes: 14

Related Questions