DotNet Mirror
  DNM facebook   DNM Google+   DNM Twitter   

can finally block have return statement

By Ashok Nalam on 11 Jul 2013 | Category: C# | Tagged: exception error 
  Discuss Add Comment   |  
Add rating Rate this resource   
No. Finally block can not have return statement. If we write return statement in finally block, compiler throws error as "Control cannot leave the body of a finally clause". To understand it easily, we will see the example.
namespace DotNetMirror
{
    class FinallyReturn
    {
        public static void Main()
        {
            Console.WriteLine(Foo());
            Console.ReadKey();
          
        }
        public static string Foo()
        {
            string str = "string before try block";
            Console.WriteLine("I am before try block");
            try
            {
                Console.WriteLine("I am in try block");
                return "return from try block";
            }
            catch
            {
                str = "return from catch block";
                return "return from catch block";
            }
            finally
            {
                Console.WriteLine("I am in finally block");
                str = "return from finally block";
                //return str; // compile-error: Control cannot leave the body of a finally clause
            }
            Console.WriteLine("I am outside try block");  // warning: Unreachable code  detected.Due to return statement in catch block
            return str;
        }
    }
}

Output:

I am before try block
I am in try block
I am in finally block
return from try block

Observations:
  • try/catch block can have return statement but finally block cannot
  • Writing return statement in finally block, throws compile time error as "Control cannot leave the body of a finally clause"
  • Even though there is a return statement in try block, still finally block executes. You can observe from the output.
  • If try block has return statement, then code after finally block does not execute. That's why string "I am outside try block" is not printed in console output.
Note: If you add throw new Exception("raise exception"); before return statement of try block, then output will be
I am before try block I am in try block I am in finally block return from catch block

  Discuss Add Comment    
Add rating Rate this resource   
About the Contributor
Member Since : 10 Dec 2012
Member Points (Level) : 8666  (Professional)
Location : INDIA
Home Page : http://dotnetmirror.com
About : I am admin of this site.
Rate this resource
 
Add your Comment
Name Email WebSite
Captcha Refresh


Comments (0)
No comments found, click here to add comment.