Example with multiple catch blocks


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//Program with multiple catch blocks
namespace CAExceptions
{
    class Exception4
    {
        static void Main()
        {
            int a, b, c;
            Console.WriteLine("Enter Any Two Numbers");
            try
            {
                a = Convert.ToInt32(Console.ReadLine());
                b = Convert.ToInt32(Console.ReadLine());
                c = a / b;
                Console.WriteLine("Quotient value is:-"+c);
            }
            catch (FormatException Ex)
            {
                Console.WriteLine(Ex.Message);
            }
            catch (DivideByZeroException Ex)
            {
                Console.WriteLine(Ex.Message);
            }
            Console.ReadLine();
        }
    }
}



Output :-


  • Whenever we write multiple catch blocks, at any point of time only one catch block will be executed and other catch block(s) will be ignored
  • Whenever multiple catch blocks are used, it is not possible to write the catch blocks in the following way and raises compilation error because first catch block Exception class only handles all the exceptions
           try
         {
               Code…
         }
        catch (Exception ex)
       {
             Code…
        }
       catch(DivideByZeroException  ex)
       {
          Code
        }

No comments:

Post a Comment