开发者

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

开发者 https://www.devze.com 2023-01-19 09:20 出处:网络
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:

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 ne开发者_C百科ver seen a working example. Anybody know how this is done reliably?


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.


There is no way to catch StackOverflowException, but you can do something with unhandled exception:

static void Main()
{
AppDomain.CurrentDomain.UnhandledException += 
  new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
}

static void CurrentDomain_UnhandledException
  (object sender, UnhandledExceptionEventArgs e)
{
  try
  {
    Exception ex = (Exception)e.ExceptionObject;

    MessageBox.Show("Whoops! Please contact the developers with the following" 
          + " information:\n\n" + ex.Message + ex.StackTrace, 
          "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
  }
  finally
  {
    Application.Exit();
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消