Answer:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("\t\tHandling Exceptions Program");
Console.WriteLine("\n\tArithmetic Exception:\n");
// Arithmetic Exception is base class of DivideByZero Class
// Hence will be using DivideByZero Exception
int b = 0;
try
{
//Attempting Divide BY Zero
int myBadMath = (5 / b);
}
catch (System.DivideByZeroException ex)
{
Console.WriteLine("Error : Trying to divide a number by Zero");
}
//FormatException example
//Used when formats DO NOT match a data type
Console.WriteLine("\n\tFormat Exception:\n");
Console.WriteLine("Please enter a number :");
string str = Console.ReadLine();
double dNo;
try
{
//throws exception when a string is entered instead of a number
dNo = Convert.ToDouble(str);
Console.WriteLine(dNo+" : Is a valid number");
}
catch (FormatException ex)
{
Console.WriteLine("Error : "+str+" is not a valid number");
}
//IndexOutOfRangeException example
//Thrown when an element is attempted to assign or read out of the array size
Console.WriteLine("\n\tIndexOutOfRangeException Exception:\n");
try
{
//5 element array declared
int[] IntegerArray = new int[5];
//attempting 10th element. Hence error is thrown
IntegerArray[10] = 123;
}
catch (IndexOutOfRangeException)
{
Console.WriteLine("An invalid element index access was attempted.");
Console.Read();
}
}
}
}
Explanation: