Exception, Try, Catch – C# Programming Questions

C# tricky and conceptual programming questions and answers with explanation asked in technical interviews.
Topic – Exception handling, Try, Catch and Throw.


Q- What is return value of the function foo()?

class xyz
{
    public int foo()
    {
        try
        { 
            return 5;
        }
        finally
        {
            
        }
      
        return 20;
    }
}

 

Answer: The foo() function will return 5.

Explanation: The constrol always comes in finally block, executes statements inside it and returns from it. Hence, “return 20;” statement will never execute.

There will be no compiler error and successfully get the result. But, compiler will warn that “uncreachabe code detected”.

NOTE : In finally block we can not have return statement or else compiler will flash an error i.e. “Error:Control cannot leave the body of a finally clause”.




Leave a Comment