Exceptions lose part of stacktrace in try/catch context
What you're seeing in the Visual Studio debugger is the unhandled exception that the Visual Studio Hosting Process is trapping (ie everything after the first two stack frames is part of that VS "host plumbing"). If you disable the hosting process (Project Properties->Enable Visual Studio hosting process), you'll see a "short" stack trace in both scenarios (notwithstanding that you won't see the stack frame for Main
in your second case because the exception is "handled", not allowed to propagate up to Main
). This shorter stack trace is the stack trace you would see if you were running the application outside the debugger.
The stack works as you would imagine - each method call pushes another stack frame onto it, and at the end of the method its stack frame is "popped", or removed from the stack. The stack trace you see on the exception is composed of the stack frames from the frame where the exception was thrown, back to the frame where the exception is ultimately handled, as the stack is "unwound".
If you need the full stack trace you can use:
catch(Exception ex)
{
var log = ex.ToString() + Environment.NewLine + new System.Diagnostics.StackTrace(true);
}
You'll probably get a much longer trace than you need. To get a shorter trace you can use:
var NL = Environment.NewLine;
var stack = new StackTrace(true).ToString().Split(new[] { NL }, StringSplitOptions.None).Take(5);
var log = ex.ToString() + NL + String.Join(NL, stack) + NL + " ...";