Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 823
Angela Avatar asked Aug 28 '12 09:08

Angela


People also ask

Does finally run after return in catch?

Yes, the finally block will be executed even after a return statement in a method. The finally block will always execute even an exception occurred or not in Java.

Does the finally block get executed if either of try or catch blocks return the control?

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.

Does finally execute without catch?

Yes, we can have try without catch block by using finally block. You can use try with finally. As you know finally block always executes even if you have exception or return statement in try block except in case of System. exit().

What will happen when catch and finally block return value?

When catch and finally block both return value, method will ultimately return value returned by finally block irrespective of value returned by catch block.


2 Answers

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

like image 172
Mitch Wheat Avatar answered Oct 11 '22 12:10

Mitch Wheat


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)

like image 39
dknaack Avatar answered Oct 11 '22 13:10

dknaack