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”.


Q- What is output of the below program?

class A
{
    public void function()
    {
        try
        {
            Console.WriteLine("Try block");

            return;
        }
        finally
        {
            Console.WriteLine("Finally block");

        }        
    }
}
class Program
    {
        static void Main(string[] args)
        {
            A c = new A();
            c.function();
        }
    }

Answer:

             Output:

Try block
Finally block

Explanation : This sounds like control will get out of the function because of return statement in try block, but this is not true and control will come in finally block too. Hence, finally block statement executes.

Rule : The statements in finally block always execute.


Related Posts