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.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
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.
Here is my solution,
Seems to work:
I agree with Michael - StackOverflowException is a signal that something went very wrong. Swallowing it is not a good idea. The best course of action is to fix the root cause of this error.
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