try/catch java 中的堆栈溢出?
你能尝试/捕获java中的堆栈溢出异常吗?它似乎正在以任何一种方式投掷自己。当我的程序溢出时,我想“惩罚”该值。
Can you try/catch a stack overflow exception in java? It seems to be throwing itself either way. When my procedures overflows, I'd like to "penalize" that value.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
似乎有效:
Seems to work:
如果出现堆栈溢出,则可能是在尝试无限递归或严重滥用函数调用。也许您可能会考虑使某些过程迭代而不是递归,或者仔细检查递归过程中是否有正确的基本情况。捕获堆栈溢出异常是一个坏主意;你只是在治疗症状,却没有解决根本原因。
If you are getting a stack overflow, you are likely attempting infinite recursion or are severely abusing function invocations. Perhaps you might consider making some of your procedures iterative instead of recursive or double-check that you have a correct base case in your recursive procedure. Catching a stack overflow exception is a bad idea; you are treating the symptoms without addressing the underlying cause.
您必须捕获错误,而不是异常
You have to catch an Error, not the Exception
Java 8 的功能特性使得这个问题变得无比重要。因为当我们开始大量使用递归时,StackOverflowException 是我们必须考虑的问题。
Java 8 lambda 类型中没有一个会抛出 StackOverflowException。所以,我们必须创建这样的。这是绝对必要的,没有它我们连IDE控制都无法通过。
例如,整数->整数函数类型可以如下所示:
之后我们可以编写一个接受 lambda 并抛出 StackOverflowException 的函数。
现在我们才可以创建一个递归 lambda:
之后我们可以调用递归链
fiboSequence.get(i)
并获取结果,如果整个链不可计算,则获取 StackOverflowException。在使用递归的情况下,SO 的含义完全不同:你跳得太深了,以更浅的步骤重复它。
The functional features of Java 8 makes this question incomparably more important. For while we start to use recursion massively, StackOverflowException is something we MUST count for.
The Java 8 lambdas types has no one among them that throws StackOverflowException. So, we have to create such. It is absolutely necessary, without that we won't pass even the IDE control.
For example, Integer -> Integer function type could look as:
After that we can write a function that will accept lambdas throwing StackOverflowException.
And only now we can create a recursive lambda:
After that we can call the recursive chain
fiboSequence.get(i)
and get a result or a StackOverflowException if the whole chain was incomputable.In the case of use of recursion SO gets absolutely different meaning: you have jumped too deep, repeat it dividing in more shallow steps.
有时,由于代码的性质,只是需要增加(取决于操作系统)堆栈大小,在 Linux 上通常为每个线程 1m。
如果您很高兴代码针对您的用例进行了优化,但仍然遇到此错误,则可以使用 -Xss2m 增加 VM 的堆栈大小 - 请参阅 Oracle 文档
Sometimes it's just required due to the nature of the code to increase the (OS dependent) stack size, which is usually 1m per thread on Linux.
If you are happy that the code is optimized for your use case and still hit this error then increase the stack size for the VM using -Xss2m for example - See the Oracle docs