Can Multiple Catch Blocks execute in c#?

0 votes
201 views
Navya Khurana asked 19-Dec-2017 in Technology by Navya Khurana

Can Multiple Catch Blocks execute in c#?

1 Answer

0 votes
Harsh kumar srivastava answered 19-Dec-2017 by Harsh kumar srivastava

Hi Navya,

In C# only one Catch block executed at a time, but you can use multiple Catch block in your method. I think it's not good enough, So now we detailed this phenomenon. 

using System;  

class Demo{
    public static void Main() {
        int a = 0;
        int division = 0;
        try {
            division = 100 / x;
            Console.WriteLine("Line is not executed");
        } catch (DivideByZeroException exDev) {
            Console.WriteLine("DivideByZeroException");
        } catch (Exception e) {
            Console.WriteLine("Exception");
        } finally {
            Console.WriteLine("Finally Block Executed");
        }
        Console.WriteLine("Solution is {0}", division );
    }

In C# you can use multiple catch block for a try block, but when try block statement is executed, All Catch block match exception type with their signature, and execute only one catch block at a time whose signature matches exception type. That's why we can say that Only one Catch block executed at a time.

I Hope it's Informative...