C# - 如何处理/捕获 StackOverFlowException?
我不需要从递归方式切换到非递归方式的课程,我只是想知道为什么我们不能处理这种类型的异常。无论如何,我在非常大的列表上使用递归函数。
我已经编写了代码来尝试捕获 StackOverFlowExceptions:
try { recursiveFxn(100000); }
catch(Exception){}
private void recursiveFxn(int countdown)
{
if (countdown > 0)
recursiveFxn(countdown - 1);
else
throw new Exception("lol. Forced exception.");
}
但我仍然遇到程序崩溃(在 NUnit 和我正在运行的网页中)。为什么没有捕获异常?
I don't need a lesson in switching from recursive to non-recursive means, I just want to know why we can't deal with this type of exception. Regardless, I'm using recursive functions on very large lists.
I have written code to attempt to catch StackOverFlowExceptions:
try { recursiveFxn(100000); }
catch(Exception){}
private void recursiveFxn(int countdown)
{
if (countdown > 0)
recursiveFxn(countdown - 1);
else
throw new Exception("lol. Forced exception.");
}
But still I get program crashes (in both NUnit and a webpage I'm running). Why isn't the exception caught?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法捕获堆栈溢出异常,因为当它发生时,它会杀死线程。 Try...catch...由同一线程执行,因此不起作用。可能有一些较低级别的 API,您可以 P/Invoke 并让另一个线程捕获它。
可能还有一些较低级别的 API 可以更改最大堆栈大小,但我在 .NET Framework 中没有看到任何可以帮助解决此问题的内容,因此您再次需要 P/Invoke 某些内容。
You can't catch a stack overflow exception because when it happens it kills the thread dead. Try... catch... is performed by the same thread so that won't work. There may be some lower level APIs that you could P/Invoke and have another thread catch it.
There may also be some lower level APIs to change the maximum stack size, but I don't see anything in the .NET Framework to help with that so again you would need to P/Invoke something.
从 .NET Framework 2.0 开始,无法捕获 StackOverflowException。这是因为这被认为是一种不好的做法。引用 MSDN 文档:
现在,捕获 StackOverflowException 的唯一方法是当用户代码抛出该异常时,如 贾里德·帕森斯的博客。除此之外,通过托管 CLR,您可以处理(但不能catch) 一个 StackOverflowException 并设计一种方法让程序继续执行。
请注意,由于发生异常时堆栈会展开,因此在 2.0 之前的 .Net 版本中,处理 StackOverflowException 时堆栈实际上会短得多,这样就可以在不生成另一个
StackOverflowException
的情况下执行此操作。代码>StackOverflowException。Since .NET Framework 2.0,
StackOverflowException
cannot be caught. This is because it is considered a bad practice. Quoting the MSDN documentation:Now, the only way to catch a
StackOverflowException
is when it was thrown by user code, as explained in a blog by Jared Parsons. Other than that, by hosting the CLR, you can handle (but not catch) aStackOverflowException
and devise a way to let the execution of your program continue.Note that because the stack is unwound when an exception occurs, in pre-2.0 versions of .Net the stack would actually be much shorter when the
StackOverflowException
is handled, making it possible to do so without generating anotherStackOverflowException
.