February 12, 2012

Multiple catch statements for single try in C#

If i am trying to write multiple catch statement for single try then what will happen.
Let’s try to write a simple program for this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestOutput
{
    class CheckOutput
    {
        public void TryCatchExecution()
       
{
            int X, Y,Result;

            X = 5;
            Y = 0;

            try
            {
                Result = X / Y;
           
}
            catch(DivideByZeroException objEx)
            {
                Console.WriteLine("Inside Specific Catch");
            }
            catch(Exception objEx)
            {
                Console.WriteLine("Inside Generalized Catch"); 
            }
            Console.ReadLine(); 
        
        }
    }
}


Now try to run this program:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestOutput
{
    class Program
    {
        static void Main(string[] args)
        {
            CheckOutput objOutput = new CheckOutput();
            objOutput.TryCatchExecution(); 
        }
    }
}

Output of this program will be:
Inside Specific Catch.

That’s It.
Enjoy Learning.

No comments:

Post a Comment