Search This Blog

Friday, April 3, 2009

StackOverflowException aka “The Uncatchable”

Ever wrote a great little application just to find that at some odd moment calling into a third party DLL throws a nice little StackOverflowException.  Then you go start digging into your code only to find that your call to this third party DLL is surrounded by not only one but two to three try/catch/finally blocks at different levels.  Hmm…weird.

The below code can quickly get this error for you and no matter if you surround it one or even 10 try/catch blocks, it will still throw the exception.

class Program
{
static void Main(string[] args)
{
try
{
Recurse();

Console.WriteLine("No exception thrown");
}
catch (StackOverflowException e)
{
Console.WriteLine("No exception caught");
}
}

private static void Recurse()
{
Recurse();
}
}

image


Does the catch block not catch StackOverflowException?

The answer is simple…only after you think about it for a little while.  No! The StackOverflowException cannot be caught by the .NET runtime because simply…according to Microsoft .NET it is bad coding practice.


Below is extracted from http://msdn.microsoft.com/en-us/library/system.stackoverflowexception.aspx.







Version Considerations

In prior versions of the .NET Framework, your application could catch a StackOverflowException object (for example, to recover from unbounded recursion). However, that practice is currently discouraged because significant additional code is required to reliably catch a stack overflow exception and continue program execution.


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. Consequently, users are advised to write their code to detect and prevent a stack overflow. For example, if your application depends on recursion, use a counter or a state condition to terminate the recursive loop. Note that an application that hosts the common language runtime (CLR) can specify that the CLR unload the application domain where the stack overflow exception occurs and let the corresponding process continue. For more information, seeICLRPolicyManager Interface and Hosting the Common Language Runtime.



I found two great articles on how to handle the StackOverflow exception:



  1. http://stackoverflow.com/questions/206820/how-do-i-prevent-and-or-handle-a-stackoverflowexception-c

  2. AppDomains.pdf

No comments:

Post a Comment