Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a good general way of catching a StackOverflow exception in C#?

If I have a method that I know could potentially recurse infinitely, but I can't reliably predict what conditions/parameters would cause it, what's a good way in C# of doing this:

try
{
  PotentiallyInfiniteRecursiveMethod();
}
catch (StackOverflowException)
{
  // Handle gracefully.
}

Obviously in the main thread you can't do this, but I've been told a few times it's possible to do it using threads or AppDomain's, but I've never seen a working example. Anybody know how this is done reliably?

like image 306
Flynn1179 Avatar asked Dec 16 '22 21:12

Flynn1179


1 Answers

You can't. From MSDN

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, see ICLRPolicyManager Interface and Hosting Overview.

like image 105
Arcturus Avatar answered May 10 '23 20:05

Arcturus