I was trying to “measure” stack depth. Why the following program doesn’t print anything?
class Program
{
private static int Depth = 0;
static void A(object o)
{
Depth++;
A(o);
}
static void B(object o, bool e)
{
Console.WriteLine(Depth);
}
static void Main(string[] args)
{
RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(A, B, null);
}
}
Some answers simply include a quote from MSDN, like “Starting with the .NET Framework version 2.0, a StackOverflowException object cannot be caught by a try-catch block and the corresponding process is terminated by default.” Believe me, sometimes (when there is enough stack space) it can be cought, the following prints some number just fine:
class Program
{
private static int depth = 0;
static void A(object o)
{
depth++;
if (Environment.StackTrace.Length > 8000)
throw new StackOverflowException("Catch me if you can.");
A(o);
}
static void B(object o, bool e)
{
Console.WriteLine(depth);
}
static void Main(string[] args)
{
RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(A, B, null);
}
}
If you want to catch it, load it into another process (that calls-back to yours via remoting) and lets the miscreant code execute there. The other process may terminate, and you could get a neat SOE popping out the end of the pipe on your side – without the adverse effects of the rather inconvenient exception.
Note that a separate AppDomain in the same process won’t cut it.
If you want to get the stack trace from an exception the following code will do you great justice: