Can multiple catch blocks be executed ?

One of my acquaintance asked this question. Initially I got confused that is it really possible.
The answer to this question is "NO". Here is a program in support with this answer.

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int numerator = 20;
                int denominator = 0;
                int result = numerator / denominator;
            }
            catch (DivideByZeroException de)
            {
                Console.WriteLine("You are trying to divide by number 0");
            }
            catch (Exception ex)
            {
                Console.WriteLine("This is a general exception.");
            }
            finally
            {
                Console.WriteLine("You are in finally block.");
            }
        }
    }

The output of this program is;
You are trying to divide by number 0
You are in finally block.

This means that when an exception occurs, and is handled with the specific type it executes the statements in the catch block and leaves the control to finally block, if exists.

It is not possible to execute multiple catch blocks.

1 comment:

  1. This is same as you perform function execution with multiple overload. The closer the overload the better chance of it getting executed. The only thing that remains constant though is that it will execute only one function at a time.

    ReplyDelete