Search code examples
vb.netvisual-studioexceptionstack-overflow

Function Calling Itself, Can't Dodge StackOverflow Error


I understand that this is bad programming practice and redundant coding but I am curios.

I am simply counting a number up to 9999999 in a while loop. The Add() function simply increases that number and prints it out.

Inside the Add() Function I call the Add() function.

My program successfully prints out 12000ish numbers before I get a StackOverflow Exception.

So my question = Is there any way to ignore this error and keep counting?

I have tried On Error Resume, Try/Catch, and throw

My code is as follows.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    While number1 < 9999999
        Try
            add()
        Catch ex As StackOverflowException
            ''Do Stuff here
        End Try
    End While
End Sub


  Function add()
    number1 = number1 + 1
    Trace.WriteLine(number1) ''Error is throw here
    add()
    Return number1
End Function

Solution

  • Since VB.NET does not support tail recursion, there is no way you can make an infinite recursion without eventually overflowing the stack.