How does Java handle division by zero?

zduny picture zduny · Jan 21, 2014 · Viewed 40.4k times · Source

Does it simply check if divisor is different from zero every time there is division done (even in JIT-ed code)?

I mean how VM manages to throw an exception without being previously killed by the OS?

Answer

BRPocock picture BRPocock · Jan 21, 2014

In an Unix environment, in which division-by-zero is signalled via SIGFPE, the JVM will have installed a signal handler which traps the SIGFPE and in turn throws an ArithmeticException. If you're interested in the internals, see e.g. man signal

What I believe the OP is asking is based on the fact that, until/unless a SIGFPE handler is in place, most processes will take the default action on receiving this signal, which is to terminate. Thus, e.g. a C program

 int main (int argc, char** argv) { int n = 5 / 0; } 

… if it even compiles, will be killed by the default SIGFPESIG_DFL action. The JVM's handler instead issues the (catchable) RuntimeException so that these exceptions can be handled in a native-seeming way.

As several others pointed out, and just for completeness, in point of fact the SIGFPE generated from the kernel is generally mapped from a special interrupt from the processor itself; thus, the “pipeline” is something like

  • CPU error trap interrupt → kernel interrupt handler → SIGFPE SIG_DFL → process death

or

  • CPU error trap interrupt → kernel interrupt handler → SIGFPE handler in JVM → RuntimeException ArithmeticException in user code

On non-Unix platforms the handling is analogous.