Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exceptions lose part of stacktrace in try/catch context

I have two examples. In the first case, debugger catches the unhandled exception:

static void Main(string[] args) {
    Exec();
}
static void Exec() {
    throw new Exception();
}

And the exception has full stacktrace:

   at ConsoleApplication28.Program.Exec() 
   at ConsoleApplication28.Program.Main(String[] args) 
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

The second case:

static void Main(string[] args) {
    Exec();
}
static void Exec() {
    try {
        throw new Exception();
    }
    catch (Exception ex) {
    } // Breakpoint
}

At the breakpoint the exception has short stacktrace:

   at ConsoleApplication28.Program.Exec()

Why stacktraces are cut to the containing method in the second case, and how to prevent it? I need full stacktrace for bugreports, otherwise it's not possible sometimes to find there the problem is, without full stacktrace.

like image 531
Alex Butenko Avatar asked Jun 19 '14 01:06

Alex Butenko


Video Answer


1 Answers

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".

like image 157
lesscode Avatar answered Oct 01 '22 08:10

lesscode