Can any one tell me can try block throw the more than one exception at a time... if is possible than how can handle them....?
like below program
using System;
class Test
{
static void Main()
{
try
{
throw new DivideByZeroException();
throw new IndexOutOfRangeException();
}
catch (DivideByZeroException e)
{
Console.WriteLine(e.Message);
}
catch (IndexOutOfRangeException s)
{
Console.WriteLine(s.Message);
}
Console.ReadKey();
}
}

Zoran HorvatPosted Jul 8, 2011, 6:24 AM
This may be a bit confusing to you, unless you understand how call stacks with exceptions work.
Imagince classical program without exceptions. Call stack looks like this:
function f (called from function g)
function g (called from main function)
function main
Now if we introduce try-catch blocks, then they are inserted into call stack. If function g has try-catch from within which it calls function f, then call stack looks like this:
1. function f (called from within try-catch from g)
2. catch block handling IndexOutOfRangeException - points to address in g function on which catch block begins
3. function g (called from try-catch from main function)
4. catch block handling DivideByZeroException - points to address in main function on which catch block begins
5. function main
Now if f throws DivideByZeroException, call stack unwinds - parts 1-3 are popped up and catch block for DivideByZeroException is reached. Then it is examined to find jump addres within main function, which actually handles the exception. After that block 4 is also popped up from stack, so that call stack looks like this:
function main
... and execution continues from the first line of catch block for DivideByZeroException.
As a result of this, line throw new IndexOutOfRangeException() cannot be reached.
Zoran
VulpesPosted Jul 8, 2011, 7:00 AM
using System;
class Test
{
static void Main()
{
try
{
try
{
throw new DivideByZeroException();
}
catch (DivideByZeroException e)
{
Console.WriteLine(e.Message);
}
throw new IndexOutOfRangeException();
}
catch (IndexOutOfRangeException s)
{
Console.WriteLine(s.Message);
}
Console.ReadKey();
}
}
The output is:
Attempted to divide by zero.
Index was outside the bounds of the array.