如何处理 StackOverflowException

How to handle a StackOverflowException

考虑这段代码:

[GlobalErrorBehaviorAttribute(typeof(GlobalErrorHandler))]
public class Service1 : IService1
{
    public string Recursive(int value)
    {
        Recursive(value);
        return string.Format("You entered: {0}", value);
    }

这是我的 GlobalErrorHandler:

public class GlobalErrorHandler : IErrorHandler
{
    public bool HandleError(Exception error)
    {
        string path = HostingEnvironment.ApplicationPhysicalPath;

        using (TextWriter tw = File.AppendText(Path.Combine(path, @"d:\IIS.Log")))
        {
            if (error != null)
            {
                tw.WriteLine("Exception:{0}{1}Method: {2}{3}Message:{4}",
                    error.GetType().Name, Environment.NewLine, error.TargetSite.Name,
                    Environment.NewLine, error.Message + Environment.NewLine);
            }
            tw.Close();
        }

        return true;
    }

    public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
    {
        var newEx = new FaultException(
                     string.Format("Exception caught at GlobalErrorHandler{0}Method: {1}{2}Message:{3}",
                                  Environment.NewLine, error.TargetSite.Name, Environment.NewLine, error.Message));

        MessageFault msgFault = newEx.CreateMessageFault();
        fault = Message.CreateMessage(version, msgFault, newEx.Action);
    }
}

当我在 WCF 测试客户端中调用 Recursive 时出现此错误。为什么我不能处理 WhosebugException?

有什么办法可以处理这样的错误吗?

根据MSDN

Starting with the .NET Framework 2.0, you can’t catch a WhosebugException object with a try/catch block, and the corresponding process is terminated by default. Consequently, you should write your code to detect and prevent a stack overflow.

在这种情况下,这意味着您应该通过传入一个整数来检查深度是否变低并自己抛出异常,从而主动防止异常,如下所示:

public string Recursive(int value, int counter)
{
    if (counter > MAX_RECURSION_LEVEL) throw new Exception("Too bad!");

    Recursive(value, counter + 1);
    return string.Format("You entered: {0}", value);
}

或重写算法以使用 tail recursion