Try with multiple catch C# program example

Learn how to handle multiple exceptions that occur in a try block in different situation using try with multiple catch.

Try with multiple catch block in c# programs is required to handle different types of exceptions with in a try block.

For examples,

if you are trying to perform some arithmetic operations e.g division operation and addition operation.

In some situations there is a chance to get Zero Divide Exception if you are trying to divide by zero,

an, Overflow Exception if you are trying to perform addition or multiplication operation with maximum value of a datatype,

and index out of range exception if you are using more than the array size.


To handle above mentioned situations we can use Multiple catch block for a try block.

 /*C# program show control flow of 
 * try with multiple catch block where 
 * Exception occur in try block
 * and different types of exception can be seen in multiple catch block
 */
    class Exceptions
    {
        static void Main(string[] args)
        {
            try
            {
                int val1 = Int32.MaxValue;
                int val2 = Int32.MaxValue;
                int val3 = 0;
                int val4;
                int[] s = { 10, 20 };

               // ArithmeticException: / by zero

                //ArithmeticException: / by Overflow
                int div = val1 / val3;

                 val4=checked(val1+val2);

           //  ArrayIndexOutOfBoundsException:
                 Console.WriteLine(s[3]);


            }
            catch(ArithmeticException Ex)
            {
                Console.WriteLine(Ex);
            }
            catch(IndexOutOfRangeException Ex)
            {
                Console.WriteLine(Ex);
            }
            catch
            {
                Console.WriteLine("unknow Exception");

            }
        }
    }

Related Posts