Friday, 10 January 2014

C# Multiple Catch Block Program.......|||||||||||||||||||||||||||||\\

C# Code:


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

namespace MultipleCatchProgram
{
    class MultipleCatchBlockExample
    {
        public void execute()
        {
            try
            {

                double val1 = 0;
                double val2 = 121;
                Console.WriteLine("Dividing {0} by {1}", val1, val2);
                Console.WriteLine("{0}/{1}={2}",val1,val2, DivideValues(val1, val2));
            }
                // most specific exeption
            catch (DivideByZeroException ex)
            {
                Console.WriteLine("DivideByZeroException Caught!");
            }
            catch (ArithmeticException e)
            {
                Console.WriteLine("ArithmeticException Caught!");
            }
                //geniric exception type last
            catch
            {
                Console.WriteLine("Unknown Exception");
            }

        }
        // do the division if legal
        public double DivideValues(double val1, double val2)
        {
            if (val2 == 0)
            {
                DivideByZeroException dx = new DivideByZeroException();
                Console.WriteLine(dx.Message);
            }
            if (val1 == 0)
            {
                DivideByZeroException ax = new DivideByZeroException();
                Console.WriteLine(ax.Message);
            }
            return val1 / val2;
        }
        public class MultipleCatchBlockExampleTest
        {
            public static void Main(string[] args)
            {
                MultipleCatchBlockExample mcbObj = new MultipleCatchBlockExample();
                Console.WriteLine("This is an example of multiple catch blocks and each catch block / handles errors/exceptions of a certain type thrown in the application.\n");
                mcbObj.execute();
                Console.ReadKey();
            }
        }
    }
}
Output:

No comments:

Post a Comment