开发者

try/catch on stack overflows in java?

开发者 https://www.devze.com 2022-12-25 02:59 出处:网络
Can you try/catch a stack overflow exception in java?It seems to be throwing itself either way.When my procedures overflows, I\'d l开发者_如何学Goike to \"penalize\" that value.Seems to work:

Can you try/catch a stack overflow exception in java? It seems to be throwing itself either way. When my procedures overflows, I'd l开发者_如何学Goike to "penalize" that value.


Seems to work:

public class Test {

    public static void main(String[] argv){
        try{
            main(null);
        }
        catch(StackOverflowError e){
            System.err.println("ouch!");
        }
    }

}


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


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:

@FunctionalInterface
public interface SoFunction <U> {
    public U apply(Integer index) throws StackOverflowException;
}

After that we can write a function that will accept lambdas throwing StackOverflowException.

public T get(int currentIndex) throws StackOverflowException{

And only now we can create a recursive lambda:

fiboSequence.setSequenceFunction(
            (i) ->
            fiboSequence.get(i-2).add(fiboSequence.get(i-1))
);

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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号