Hi....
I know try and catch used for exception handling in C# but I want to know,there are possible multiple try block for single catch block or multiple catch block for single try block ? Please explain with an example in details ?
Thanks....
Loading

Satyapriya NayakPosted Jan 8, 2012, 11:51 PM
Yes. Multiple catch blocks may be put in a single try block.
Example:-
using System;
public class ExcDemo4 {
public static void Main() {
// Here, numer is longer than denom.
int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 };
int[] denom = { 2, 0, 4, 4, 0, 8 };
for(int i=0; i < numer.Length; i++) {
try {
Console.WriteLine(numer[i] + " / " +
denom[i] + " is " +
numer[i]/denom[i]);
}
catch (DivideByZeroException) {
// catch the exception
Console.WriteLine("Can't divide by Zero!");
}
catch (IndexOutOfRangeException) {
// catch the exception
Console.WriteLine("No matching element found.");
}
}
}
}
But for every try block there must be a corresponding catch block.
Example:-
using System;
public class NestTrys {
public static void Main() {
// Here, numer is longer than denom.
int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 };
int[] denom = { 2, 0, 4, 4, 0, 8 };
try { // outer try
for(int i=0; i < numer.Length; i++) {
try { // nested try
Console.WriteLine(numer[i] + " / " +
denom[i] + " is " +
numer[i]/denom[i]);
}
catch (DivideByZeroException) {
// catch the exception
Console.WriteLine("Can't divide by Zero!");
}
}
}
catch (IndexOutOfRangeException) {
// catch the exception
Console.WriteLine("No matching element found.");
Console.WriteLine("Fatal error -- program terminated.");
}
}
}
Thanks
Vineet Kumar SainiPosted Jan 9, 2012, 1:58 AM
AartiPosted Jan 9, 2012, 12:19 AM
Multiple try block for single Catch block is not possible in C Sharp.
But You can define multiple catch block for single Try block.
Example:
// Ordering catch clauses
using System;
class MyClass
{ public static void Main()
{ MyClass x = new MyClass();
try
{ string s = null;
x.MyFn(s);
} // Most specific:
catch (ArgumentNullException e)
{ Console.WriteLine("{0} First exception caught.", e);
} // Least specific:
catch (Exception e)
{ Console.WriteLine("{0} Second exception caught.", e);
}
}
public void MyFn(string s)
{ if (s == null) throw new ArgumentNullException(); }
}
Jignesh TrivediPosted Jan 8, 2012, 11:43 PM
There is multiple catch block for single try block.
try
{
....
}
catch (SqlException es)
{
// catch only SQL Exception
}
catch (OutOfMemoryException eo)
{
// catch only Out Of Memory Exception
}
hope this help.