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 ?
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.
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.
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().
When catch and finally block both return value, method will ultimately return value returned by finally block irrespective of value returned by catch block.
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
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.
MSDN - try-finally (C# Reference)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With