How the Call Stack Works
Examine the output of Example 16-2 carefully. You see the code enter Main(), Method1(), Method2(), and the try block. You never see it exit the try block, though it does exit Method2(), Method1(), and Main(). What happened?
When the exception is thrown, execution halts immediately and is handed to the catch block. It never returns to the original code path. It never gets to the line that prints the exit statement for the try block. The catch block handles the error, and then execution falls through to the code following the catch block.
If there is no exception handler at all, as we discussed, the stack is unwound, returning to the calling method in search of an exception handler. This unwinding continues until the Main() method is reached, and if no exception handler is found, the default (ugly) exception handler is invoked and the program terminates.
In this example, because there is a catch block, the stack does not need to unwind. The exception is handled, and the program can continue execution. Unwinding the stack becomes a bit clearer if you move the try/catch blocks up to Method1(), as Example 16-3 shows.
Example 16-3. The catch block has now moved from Method2 to Method1, so the program needs to unwind the stack by one level before finding the handler
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Example_16_3_ _ _ _Unwinding_the_Stack { class Tester { public void Run() { Console.WriteLine("Entering Run..."); ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access