Friday, August 5, 2011

Defining Multiple Catch Blocks in console application.

You can define multiple catch blocks in sequence to catch different types of exception. When an exception occurs, the CLR examines each catch block in the order that was defined to find a catch block that can handle the exception. Therefore, you must ensure that you order the catch blocks from the most specific type to the most generic type to ensure that the CLR executes the most specific catch block for any given exception.

Following example shown.

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

namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Enter first number");
int i = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter second number");
int j = Convert.ToInt32(Console.ReadLine());
int k = i / j;

int[] ii = { 1, 2, 3, 4 };
Console.WriteLine(ii[6]);

}
catch (DivideByZeroException ex)
{
Console.WriteLine(ex);
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine(ex);
}

Console.WriteLine("Next line");
Console.ReadLine();
}
}
}
Output is display below.

No comments:

Recent Posts