C Sharp

Throwing Exceptions From Constructors

Another major advantage that exceptions have over other error-handling techniques is in the area of object construction. Because a constructor cannot return values, there's simply no easy, intuitive means of signaling to the constructor's calling method that an error occurred during object construction. Exceptions, however, can be used because the calling method need only wrap the construction of the object in a try block, as in the following code: -

try
{
    // If the AccessDatabase object fails to construct
    // properly and throws an exception, it will now be caught.
    AccessDatabase accessDb = new AccessDatabase();
}
catch(Exception e)
{
    // Inspect the caught exception.
}

Using the System.Exception Class

As mentioned earlier, all exceptions that are to be thrown must be of the type (or derived from) System.Exception. In fact, the System.Exception class is the base class of several exception classes that can be used in your C# code. Most of the classes that inherit from System.Exception do not add any functionality to the base class. So why does C# bother with derived classes if the derived classes aren't going to significantly differ from their base class? The reason is that a single try block can have multiple catch blocks with each catch block specifying a specific exception type. (You'll see this shortly.) This enables the code to handle different exceptions in a manner applicable to a specific exception type.