¿El código en a finalmente se ejecuta si tengo un retorno en mi catch() en 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 ?

preguntado el 28 de agosto de 12 a las 10:08

5 Respuestas

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 Procesamiento de excepciones no controladas en CLR.

Ref: Try-Finally

Respondido 28 ago 12, 10:08

sí el 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.

Más Información

MSDN - try-finally (C# Reference)

Respondido 28 ago 12, 10:08

Thanks - So does the finally get executed before the return or is it done asynchronously? - Angela

The finally will get executed first. - loco

Programas de finally will be executed even if there is a return within the catch bloquear

bloque finalmente siempre se ejecuta

respondido 26 mar '14, 15:03

Programas de finally will execute after the catch-block is exited (in your by means of an explicit "return"). However, everything después de the finally-block (in your case the if (vm.Detail.Any()) ...) Hará no ejecutar.

Respondido 28 ago 12, 10:08

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.

Respondido 28 ago 12, 10:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.