Thursday 22 March 2012

Multiple Catch Blocks


//Program to handle exception using try Multiple catch finally
using System;
class Program
{
static void Main()
{
int x,y,z=0;
try
{
Console.Write("Enter X: ");
x=int.Parse(Console.ReadLine());
Console.WriteLine();

Console.Write("Enter Y: ");
y=int.Parse(Console.ReadLine());
Console.WriteLine();

z=x/y;
}

catch(FormatException exp) //Called Specific Exception.Handles Only Exceptions Related to FormatException
{
Console.WriteLine("X and Y Both Must be Integer Type");
}

catch(DivideByZeroException exp) //Called Specific Exception.Handles Only Exceptions Related to DivideByZeroException
{
Console.WriteLine("You should not divide by 0");
}

catch(Exception exp) //Handles all Other Exceptions because it is known as General Exception.This must be at end of all exception Defined
//Why because it can handle all exception.So it must be at end of all Specific Exception.
{
Console.WriteLine(exp.Message);
}
finally
{
Console.WriteLine("Result: {0}",z);
}
}
}

No comments:

Post a Comment