views:

54

answers:

2

Hello,

How does JVM or for that matter CLR (Common language runtime) handles divided by zero? Does it check denominator every time, before executing divide instruction? Or is it handled using call back function which get invoked when "divide by zero" trap raised by processor?

Any input will be appreciated.

Thank you, Alan

+6  A: 

All processors I know generate a hardware trap for this. Which is handled by the operating system and reflected into the user mode code with an OS dependent mechanism (signal, exception, etc). Which the runtime picks up and translates into a Java or .NET exception.

Hans Passant
+1  A: 

It is an implementation detail, as you should not care of what happens under the hood of the virtual machine (if you had to care about it, you would lose true portability!).

However, since managed code is jitted, the division is always performed and in case of zero denominator the processor will throw a first chance exception that will be caught by the runtime and then reflected as a high level exception.

Lorenzo
+1, but I don't think there's ever any harm in knowing what goes on under the hood.
Marc Bollinger
Of course, no harm! But it is worth to stress the fact that when you don't have to know the implementation, it means that you will not run in portability issues.
Lorenzo