Using Nested Exception Handlers

When an exception is thrown, NET tries to find a matching catch statement in the current method. If the code is not in a local structured exception block or if none of the catch statements matches the exception, NET will move up the call stack one level at a time, searching for active exception handlers.

Here is an example where the Page. Load event handler calls a private DivideNumber () method:

Protected void Page_Load (Object sender, EventArgs e)
{
Try
{
DivideNumbers (6, 0);
}
Catch (DivideByZeroException err)
{
//Report Error Here.
}
}
Private decimal DivideNumbers (Decimal number, decimal Divisor)
{
Return number/divisor;
}

In the above example, the divideNumbers () method lacks any sort of exception handler. However the DivideNumbers () method call is made inside a try block, which means the problem will be caught further upstream in the calling code. This is a good approach because the DivideNumbers () routine could be used in a variety of circumstances. It really has no access to any kind of user interface and cannot directly report an error. Only the calling code is in a position to determine whether the problem is a serious one or a minor one, and only the calling code can prompt the user for more information or report error details in the web page.

You can also overlap exception handlers in such a way that different exception handlers filter out different types of problems.Here we will illustrate an example:

Protected void Page_Load (Object sender, EventArgs e)
{
Try
{
Decimal average = GetAverageCost (DateTime.Now);
}
Catch (DivideByZeroException err)
{
//Report error here.
}
}
Private decimal GetAverageCost (DateTime saleDate)
{
Try
{
//Use Database access code here to retrieve all the sale records
//for this date, and calculate the average.
}
Catch (System.Data.SqlClient.SqlException err)
{
// Handle a database-related problem.
}
Finally
{
//Close the database connection.
}
}

You should be aware of the following points in the code

If a SqlException occurs during the database operation, it will be caught in the GetAverageCost () method.

If a DivideByZeroException occurs, the Exception will be caught in the calling Page.Load event handler.

If another problem occurs, no active exception handler exists to catch it. In this case, .NET will search through the entire call stack without finding a matching catch statement in an active exception handler and will generate a runtime error, end the program, and return a page with exception information.