Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
For the below scenario, will it return R before it goes to Finally block?Or else untill it wait after the finally block is executed?
Here my requirement is need to send the response ASAP while accessing my function
'Getresponse'.Please help me on this.
C#
public ResponseMsg Getresponse(parameters...)
{
   ResponseMsg R;
    <pre lang="C#">try
        {
           //Checking some condition
        R.Acknowledgement = "1";
           Return R;

        }
        catch (Exception)
        {
            Console.WriteLine("catch");
        }
        finally
        {
//           Some Db operations..
        }

}
Regards,
Soumya

What I have tried:

C#
public ResponseMsg Getresponse(parameters...)
{
   ResponseMsg R;
    <pre lang="C#">try
        {
           //Checking some condition
 R.Acknowledgement = "1";
           Return R;

        }
        catch (Exception)
        {
            Console.WriteLine("catch");
        }
        finally
        {
//           Some Db operations..
        }

}
Posted
Updated 15-Jul-16 4:06am
v3

It will execute the return statement - i.e. it will evaluate the parameter - and then it will execute the finally block. After that it will adjust the stack and return execution (along with the value) to the calling function.
If you aren't sure, then create some dummy code and test it:
C#
private void myButton_Click(object sender, EventArgs e)
    {
    Console.WriteLine("Before");
    Console.WriteLine(ShowMe());
    Console.WriteLine("After");
    }
private int ShowMe()
    {
    try
        {
        Console.WriteLine("Try");
        return ShowReturn();
        }
    finally
        {
        Console.WriteLine("Finally");
        }
    }
private int ShowReturn()
    {
    Console.WriteLine("ShowReturn");
    return 1;
    }

You will get:
Before
Try
ShowReturn
Finally
1
After
Which shows the order quite nicely.
 
Share this answer
 
The finally block will be executed also for the return Statement(s) in between the code. But from my Point of view "Returns" in between the code is a usually bad Praxis.

Details you can find here:
try...catch...finally Statement[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900