函数调用自身,无法避免 StackOverflow 错误
我知道这是糟糕的编程实践和冗余编码,但我很好奇。
我只是在 while 循环中计算直到 9999999 的数字。 Add()
函数只是增加该数字并将其打印出来。
在 Add()
函数内,我调用 Add()
函数。
在出现 StackOverflow 异常之前,我的程序已成功打印出 12000 左右的数字。
所以我的问题=有没有办法忽略这个错误并继续计数?
我尝试过 On Error Resume
、Try/Catch
和 throw
我的代码如下。
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
吗?没有。您唯一能做的就是从一开始就避免引起它。大多数时候,StackOverflowException 是无法捕获的。来自 MDSN:
No. The only thing you can do is avoid causing it in the first place. Most of the time, StackOverflowExceptions are uncatchable. From MDSN:
由于 VB.NET 不支持尾递归,因此您无法在不使用尾递归的情况下进行无限递归。最终导致堆栈溢出。
Since VB.NET does not support tail recursion, there is no way you can make an infinite recursion without eventually overflowing the stack.
您永远不会从函数中返回:
因此,
add
调用add
调用add
- 在某些时候您会破坏堆栈。您需要某种退出条件来测试。例如:
You never return from the function:
So,
add
callsadd
callsadd
- at some point you are blowing the stack. You need some sort of exit condition to test for.For example:
将您的方法从以下更改:
改为:
保持代码的其余部分相同,并且不会发生堆栈溢出。
Change your method from this:
To this:
Keep the rest of your code the same and the stack overflow will not happen.