[Previous] [Contents] [Next]

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.
}

[Previous] [Contents] [Next]