The Structured exception handling is particularly flexible because it allows you to catch specific types of exceptions. To do so, you Add multiple catch statement, each one identifying the type of exception (and providing a new variable to catch it in), as follows:
Try
{
//Risky database code goes here.
}
Catch (System.Data.SqlClient.SqlException err)
{
//Catches common problems like connection errors.
}
Catch (System.NullRefernceException err)
{
//Catches problems resulting from an uninitialized object.
}
An exception will be caught as long as it is an instance of the indicated class or if it is derived from the class. In other words, if you use this statement:
Catch (Exception err)
You will catch any exception because every exception object is derived from the System. Exception base class.
Exception blocks work a little like conditional code. As soon as a matching exception handler is found, the appropriate catch code is involved. Therefore, you must organize your catch statements from most specific to least specific:
Try
{
//Risky database code goes here.
}
Catch (System.Data.SqlClient.SqlException err)
{
//Catches common problems like connection errors.
}
Catch {Sytem.NullReferenceException err)
{
//Catches problem resulting from an uninitialized object.
}
Catch (System. Exception err)
{
//Catches any other errors.
}