Click here to Skip to main content
15,904,023 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Below is my program.

C#
class Program
    {
        int ret = default(int);
        static void Main(string[] args)
        {
            Program ob = new Program();
            Console.WriteLine(ob.DoSomeOperation());
            Console.WriteLine("------------------------------------");
            //Console.WriteLine(ob.ret);
            Console.ReadKey();
        }

        public int DoSomeOperation()
        {
            try
            {
                ret = 5;
                //return ret;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                ret = 9;
            }
            return ret;
        }
    }


You can see the return statement inside try and after finally.

If I uncommented the return statement in try block, DoSomeOperation method will return 5 and on the contrary it will return 9.

Please clarify me if finally block executes all the time, then why it is not returning 9 if i uncommented the return statement in try block.
Posted

Finally will run but you already returned the value in your try.

So, it does this

1. Sets ret = 5.
2. returns ret which is 5
3. Calls finally which sets ret = 9

Finally is guaranteed to run. I assume this is just some test code but if it in anyway mimics your real code you may need to make some changes.
 
Share this answer
 
Comments
DamithSL 5-Nov-14 8:48am    
Correct, 5wd!
return (C# Reference)[^]
Quote:
If the return statement is inside a try block, the finally block, if one exists, will be executed before control returns to the calling method.

So, it will execute finally block and not reach the final rerun line. (Your IDE may be showing you have unreachable line detected warning)
 
Share this answer
 
Comments
johannesnestler 5-Nov-14 8:19am    
he does not return inside the try (line was commented out) but set's a variable. A good fact to know but no solution to OP's question...
DamithSL 5-Nov-14 8:40am    
"Please clarify me if finally block executes all the time, then why it is not returning 9 if i uncommented the return statement in try block."
DamithSL 5-Nov-14 8:42am    
I think you have not read the question
Yes the finally block executes all the time - that's the reason for the finally block to exist - execute anyway - exception or not....
I have no problem with your question and answering it, but I find such basics about language syntax are better learned from a book or documentation - MSDN?
http://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx[^]
 
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