Search code examples
.netstack-overflow

Why doesn't .NET log the stack trace for StackOverflow exceptions?


If I write this:

class Program
{
    static void Main(string[] args)
    {
        throw new Exception("lol");
    }
}

and run the exe from the command line, I get two entries in my event log. One is an application error that says there was an unhandled exception, and the other contains the stack trace with the source as .NET Runtime.

If I write this:

class Program
{
    static void Main(string[] args)
    {
        Recurse4Evr();
    }

    static void Recurse4Evr()
    {
        Recurse4Evr();
    }
}

I only get one entry in my event log, which says Application Error and that there was a stack overflow exception. There isn't that second entry with the stack trace, so it's basically useless.

Why isn't the stack trace also logged? If I setup DebugDiag and attach it to my process and then there is a stack overflow, DebugDiag is able to log the stack trace. Obviously the stack trace is available to the outside world in some way. If the runtime is terminating the process because it detected a stackoverflow, then it also knows what the stack is.

In large applications that have many complex interactions, it is often not possible to recreate the conditions that led to a stack overflow. In this situation, a stack trace is the only way to figure out what happened. Why did microsoft decide it wasn't important to log this information? Was there a legitimate design decision that isn't obvious?


Solution

  • This is apparently not possible. If you want a stack trace so you can find the offending code that killed your application, you need to attach a 3rd party tool like DebugDiag or AdsPlus. Good luck, there is basically no documentation for these tools.