【问题标题】:System.StackOverflowException C#System.StackOverflowException C#
【发布时间】:2020-12-08 14:59:15
【问题描述】:

如何绕过 stackoverflow 异常,或者有更好的方法吗?非常感谢任何帮助!

public MetricItemDetail GetData(int itemId, int itemTwoId)
{

        //some of my code goes here..

         try
                {
                    return new Class
                    {
                        Value = GetItemDetails(itemId, itemIdTwo)

                    };
                }
                catch (Exception e)
                {
                    Console.WriteLine("{0} Exception caught.", e);
                    return new Class();
                }

}

public double GetItemDetails(int itemId, int itemTwoId)
{

   var currentValue = GetData(itemId, itemTwoId); // The problem is here..this is where I get the stackoverflow exception

}

【问题讨论】:

  • 我的意思是,你陷入了无限循环......
  • GetItemDetails 调用GetData,后者调用GetItemDetails。看到问题了吗?
  • is there a better way to do this? 如果你所说的“这个”是指导致堆栈溢出,那么不,你已经成功了!
  • 是的,这就是为什么我要问是否有办法绕过 stackoverflow 异常。我知道问题出在@JeroenMostert
  • 您的问题中绝对没有任何信息。你想达到什么目的?逻辑在哪里?

标签: c# recursion model-view-controller stack-overflow


【解决方案1】:

GetItemDetails 和 GetData 方法是相互调用的,它会导致“无限”循环,每次调用都会分配堆栈,不幸的是堆栈大小不是无限的;)

在此处查看更多详细信息:https://www.dotnetperls.com/stackoverflowexception

StackOverflowException 不能被绕过,不能被捕获,必须避免。它的存在是为了保护 .NET 运行时免受致命崩溃。

【讨论】:

  • unfortunatelly stack size isn't infinite 这不是我对这个问题的印象。更像是:“在某些时候你必须告诉程序该做什么”
  • @coffeetime 没必要生气,我指出这个答案是在“如果你将它增加到无限则问题得到解决”中的“有限堆栈大小”不是正确的印象这个问题的。 stackoverflow通常是在“代码中没有逻辑”并且程序没有被告知要做什么时引起的,并且程序一直在毫无目的地反复进行。
  • 我现在明白给定的代码应该演示stackowerflow原理,而不是工作代码。您可以尝试扩大堆栈内存并使用旧版本的 .NET 运行时(例如 1.1),该版本对 StackOverflowException 或 OutOfMemoryException 等异步异常更加不敏感,并允许捕获和绕过它们,风险自负。
猜你喜欢
  • 2011-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多