3

This is just my curiosity to know why java compiler doesn't show any warning in this case while it shows warning for unchecked operations to predict a probable ClassCastException.

public class DivideByZero {
    public static void main() {
        int number = 3/0;
        System.out.println(number);
    }
}

Above code is guaranteed to produce an ArithmeticException.

This is an example only. There are more ways to guarantee a runtime exception without any warning during compilation.

coder11
  • 457
  • 3
  • 9
  • 4
    Because the Java compiler is not infinitely smart. – SLaks Sep 29 '13 at 18:44
  • 2
    Related: http://stackoverflow.com/questions/2934063/is-1-0-a-legal-java-expression – Sotirios Delimanolis Sep 29 '13 at 18:49
  • Because the compiler can't dictate what is "wrong" and what is "right".You may think division by zero is wrong, but some other people could think otherwise. Getting a warning in this case, therefore, would be annoying to them. – One Two Three Apr 23 '15 at 19:42

1 Answers1

3

Because technically a divide by zero is a valid program. Compilers only determine the validity of the program not whether there will be a runtime problem. It would be technically incorrect for a compiler to not let you compile a program with a divide by zero since it's valid.

Jesus Ramos
  • 22,940
  • 10
  • 58
  • 88