¿El código en a finalmente se ejecuta si tengo un retorno en mi catch() en c#?
Frecuentes
Visto 3,252 veces
10
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 ?
5 Respuestas
14
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
10
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
Respondido 28 ago 12, 10:08
4
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
3
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
2
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 c# try-catch-finally or haz tu propia pregunta.
speedreviews.com/forums/… - Amiram Korach