C Sharp

Catching an Exception

Obviously, because a method can throw an exception, there must be a reciprocal part of this equation where something has to catch the thrown exception. The catch keyword defines a block of code that is to be processed when an exception of a given type is caught. The code in this block is referred to as an exception handler.-

One thing to keep in mind is that not every method needs to deal with every possible thrown exception, especially because a method might not have the context required to do anything with the error information. After all, the point of exception handling is that errors are to be handled by code that has enough context to correctly do so-see "Handling Errors in the Correct Context," later in this chapter. For now let's deal with situations in which a method is going to catch any thrown exceptions from the method being called. We use two keywords to catch an exception: try and catch.

To catch an exception, you need to bracket the code you're attempting to execute in a try block and then specify which types of exceptions the code within that try block is capable of handling in a catch block. All the statements in the try block will be processed in order as usual unless an exception is thrown by one of the methods being called. If that happens, control is passed to the first line of the appropriate catch block. By "appropriate catch block," I mean the block that's defined as catching the type of exception that is thrown. Here's an example of a method (Foo) calling and catching an exception being thrown by another method (Bar): -

public void Foo()
{
    try
    {
        Bar();
    }
    catch(System.Exception e)
    {
        // Do something with error condition.
    }
}

Now your next question might be, "What happens if Bar throws an exception and Foo doesn't catch it?" (This would also be the case if the call to Bar were not in a try block.) The result depends on the design of the application. When an exception is thrown, control is passed back up the call stack until a method is found that has a catch block for the type of exception being thrown. If a method with an appropriate catch block is not located, the application aborts. Therefore, if a method calls another method that does throw an exception, the design of the system must be such that some method in the call stack must handle the exception.

by BrainBellupdated
Advertisement: