In Java, is there a way to know that a StackOverflow
error or OutOfMemory
exception may happen soon?
The OutOfMemory
exception m
For StackOverflowError:
To know the current depth, usually it's either:
Knowing the depth it will occur is difficult. There are several factors:
Why not try it out using something like this?
public static void main(String[] args) {
try {
recurs();
} catch (Throwable t) {
// not a good idea in production code....
}
}
static int depth = 0;
static void recurs() {
System.out.println(depth++);
recurs();
}
Run it several times. Also try adding dummy variables. It can be seen that even the same code may halt at different depths and adding more variables cause it to end earlier. So yeah, pretty much it's unpredictable.
I suppose that besides rewriting the algorithm the only option would be to increase the stack space with the -Xss option.
For OutOfMemoryError, there's the -Xmx option