When will a StackOverError
be thrown?
Or rather, when will it not be thrown?
For example, if we use the primitive operators +
, +=
, -
, -=
, ==
<
, >
, /
, %
, etc:
try {
// operations +, +=, -, -=, == <, >, /, %, etc
} catch (java.lang.StackOverflowError e) {
// will never occur?
}
Is there any guarantee that StackOverflowError
will not be thrown?
In theory, on some weird JVM +
operator can be implemented using recursion internally by adding + 1
in a recursive loop. The other operators might also be implemented using internal method call.
I don't think it will ever be the case. In every typical JVM/architecture these operations are implemented using single operation/instruction. There are bytecode instructions for all these operators and I would expect they are translated 1:1 to assembly. But there are no guarantees in the JLS.
By the way the JavaDoc:
Thrown when a stack overflow occurs because an application recurses too deeply.
is not really correct. You can get StackOverflowError
without any recursion - if you have very deep call tree and methods have very long argument list. However this is very hard to achieve in practical terms.
The only reference to StackOverflowError
in the Java Language Specification is the following:
15.12.4.5 Create Frame, Synchronize, Transfer Control
A method
m
in some classS
has been identified as the one to be invoked.Now a new activation frame is created, containing the target reference (if any) and the argument values (if any), as well as enough space for the local variables and stack for the method to be invoked and any other bookkeeping information that may be required by the implementation [...]. If there is not sufficient memory available to create such an activation frame, an
StackOverflowError
is thrown.
The JVM spec says the following:
StackOverflowError:
The Java virtual machine implementation has run out of stack space for a thread, typically because the thread is doing an unbounded number of recursive invocations as a result of a fault in the executing program.
So, judging from the above statements...
I was wondering is it true that code which do not call any functions will never throw a java.lang.StackOverflowError?
...yes, that's true.
For example, if I use the operators
+
,+=
,-
,-=
,==
,<
,>
,/
,%
etc on primitives (including long and double),
Right. None of those will ever (by themselves) invoke a method and should therefore not cause a StackOverflowError
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With