如何处理StackOverflowException

用户1968030

考虑以下代码:

[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);
    }
}

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

有什么办法可以处理这种错误?

帕特里克·霍夫曼

根据MSDN

从.NET Framework 2.0开始,您无法使用try / catch块捕获StackOverflowException对象,并且默认情况下终止了相应的进程。因此,您应该编写代码以检测并防止堆栈溢出。

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

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);
}

或重写算法以使用尾部递归

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章