Searching for an Exception Handler

When your program encounters an exceptional circumstance, such as running out of memory, it throws an exception, as we mentioned. Exceptions must be handled before the program can continue. As we discussed, the exception handler is a catch block located somewhere in your code. It can be located in the current method, or it can be somewhere else higher up the call stack (which we defined in Chapter 9). Where the exception handler is located dictates what the program does after the exception is handled.

If the currently running method does not handle the exception, the current function terminates. Control returns to the calling function, which then gets a chance to handle the exception. If that calling function does not have an exception handler, the function that called that one gets a chance. This process is called unwinding the stack. If none of the calling functions handles the exception, including Main(), program control passes to the Common Language Runtime (CLR), which abruptly terminates your program—this is generally considered bad.

In other words, if method A calls method B, and method B calls method C, these method calls are all placed on the stack. When a programmer talks about "unwinding the stack,” she means that you back up from C to B to A, as illustrated in Figure 16-1.

You’ve seen the call stack in action in previous chapters. When an exception is thrown in method C, the program will unwind the stack until it finds an exception handler.

Figure 16-1. You’ve seen the call stack in action in previous chapters. ...

Get Learning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.