Sunday 2 October 2011

Can we put multiple catch blocks in a single try statement in C#?


              Yes. Multiple catch blocks may be put in a try block. See code example below, to see multiple catch blocks being used in C#.
C# Example
class ClassA
{
public static void Main()
{
 int y = 0;
try
{
 val = 100/y;
 Console.WriteLine("Line not executed");
}
catch(DivideByZeroException ex)
{
  Console.WriteLine("DivideByZeroException" );
}
catch(Exception ex)
{
  Console.WritLine("Some Exception" );
}
finally
{
  Console.WriteLine("This Finally Line gets executed always");
}
Console.WriteLine("Result is {0}",val);
}

No comments:

Post a Comment