Division by Zero

As you might expect, Java does not allow integer division by 0. If you include this statement in your program,

Screen Shot 2018-12-13 at 7.00.51 PM

the code will compile without errors, but at run time, when this statement is executed, the JVM will generate an exception and print an error message on the Java console:

Screen Shot 2018-12-13 at 7.14.57 PM

In most cases, this stops the program. When you learn selection techniques, you will be able to avoid dividing by zero by first testing whether the divisor is zero before performing the division. In contrast, floating-point division by zero does not generate an exception. If the dividend is nonzero, the answer is Infinity. If both the dividend and divisor are zero, the answer is NaN, which stands for “Not a Number.” The example below illustrates the three cases of dividing by zero.

Screen Shot 2018-12-13 at 8.19.55 PM

As we can see on the output shown, line 16 never executes. The exception is generated at line 15 and the program halts execution.

Screen Shot 2018-12-13 at 8.21.16 PM

Although floating-point division by zero doesn’t bring your program to a halt, it doesn’t provide useful results either. It’s a good practice to avoid dividing by zero in the first place… stupid Simulators causing black holes all over the place.