java去0,Java如何处理除零?

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?

解决方案

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 SIGFPE → SIG_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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值