尝试调用sub时出现此错误(mscorlib.dll中发生了'System.StackOverflowException'类型的未处理异常)

时间:2012-11-27 02:56:47

标签: vb.net vb.net-2010

我有一个子试图在数据库中获取随机食物,得到这些食物的卡路里总和,并检查它们是否不会超过所需的卡路里。

子工作的大部分时间,但有时会出现此错误。 这是我的代码。它有点长。

Private Sub lunchgenerate()

        Dim grams As Integer = DSgrams.Tables("grams").Rows(0).Item("grams")
        Dim grams1 As Integer = DSricegrams.Tables("ricegrams").Rows(0).Item("grams")
        Dim grams2 As Integer = DSgrams2.Tables("grams").Rows(0).Item("grams")

        Dim calorieval As Decimal = foodcalories * grams
        Dim calorieval1 As Decimal = ricecalories * grams1
        Dim calorieval2 As Decimal = foodcalories2 * grams2

        Dim carbval As Decimal = foodcarb * grams
        Dim carbval1 As Decimal = ricecarb * grams1
        Dim carbval2 As Decimal = foodcarb2 * grams2

        Dim proteinval As Decimal = foodprotein * grams
        Dim proteinval1 As Decimal = riceprotein * grams1
        Dim proteinval2 As Decimal = foodprotein2 * grams

        Dim fatval As Decimal = foodfat * grams
        Dim fatval1 As Decimal = ricefat * grams1
        Dim fatval2 As Decimal = foodfat2 * grams

        Dim caloriepercent As Decimal = usercalories * 0.5
        Dim mincalories As Decimal = caloriepercent - 300

        Dim proteinpercernt As Decimal = userprotein * 0.5
        Dim minprotein As Decimal = proteinpercernt - 20

        Dim counter As Integer = 0
        Dim counter1 As Integer = 0

        Dim foodcalorietotal As Decimal = calorieval + calorieval1 + calorieval2
        Dim foodproteintotal As Decimal = proteinval + proteinval1 + proteinval2
        Dim carbtotal As Decimal = carbval + carbval1 + carbval2
        Dim foodfattotal As Decimal = fatval + fatval1 + fatval2

        If foodcalorietotal < mincalories Or foodcalorietotal > caloriepercent Then
            counter = 0
        Else
            counter = 1
        End If

        If foodproteintotal < minprotein Or foodproteintotal > proteinpercernt Then
            counter1 = 0
        Else
            counter1 = 1
        End If

        If counter = 1 And counter1 = 1 Then
          'output to the form

        Else

                **lunchgenerate()**

            End If

        End If
End Sub

我认为错误是再次调用lunchgenerate()sub时的错误。

但就像我说的那样,大部分时间都有效,但有时会冻结,然后会出现此错误,然后突出显示我的代码的第一行

        Dim DAlunchcategory As New SqlDataAdapter(lunchquery, CN)
        Dim DSlunchcategory As New DataSet
        DAlunchcategory.Fill(DSlunchcategory, "category_id")

1 个答案:

答案 0 :(得分:1)

如果堆栈上没有空间(用于局部变量,参数值,函数结果和其他一些小东西的过程内存的一部分),则会发生

Stack Overflow错误。

产生此错误的代码通常通过执行无限递归来实现。如果您显示的代码是完整的lunchgenerate函数,则在countercounter1不为1的情况下,将lunchgenerate再次调用具有完全相同的结果,再次,直到它完全耗尽堆栈上的空间并抛出异常。你需要有一些逃避逻辑来避免它。