Section 18.2. Searching for an Exception Handler

   

18.2 Searching for an Exception Handler

When your program encounters an exceptional circumstance, such as running out of memory, it throws (or raises) an exception. Exceptions must be handled before the program can continue.

The search for an exception handler can unwind the stack. This means that if the currently running function does not handle the exception, the current function terminates and the calling function gets a chance to handle the exception. If none of the calling functions handles it, the exception ultimately is handled by the Common Language Runtime (CLR), which abruptly terminates your program.

If function A calls function B and function B calls function C, these function calls are all placed on the stack. When a programmer talks about " unwinding the stack" what is meant is that you back up from C to B to A, as illustrated in Figure 18-1.

If you must unwind the stack from C to B to A to handle the exception, when you are done, you are in A; there is no automatic return to C.

Figure 18-1. Unwinding the stack
figs/lcs_1801.gif

If you return all the way to the first method (Main) and no exception handler is found, the default exception handler (provided by the compiler) is invoked. The default exception handler just terminates the program.

   


Learning C#
Learning C# 3.0
ISBN: 0596521065
EAN: 2147483647
Year: 2005
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net