-1

sorry for bad English.
Obviously, division by zero is always undefined. So why that is an exception at run time? Why that is not a compile error ? conclusion of division by zero not changed at run time. It is different from something like file not found exception which that will be determined after execution.

        System.out.println(1/0);

Another example :

        Person firstPerson = (Person) new Object();

compiler permit parent to child cast,but it throws exception at runtime.

HFDev
  • 131
  • 2
  • 4
  • 11
  • See also http://stackoverflow.com/questions/846103/runtime-vs-compile-time – stg Apr 10 '15 at 13:50
  • I think there is no "real" answer to this. In the end, it depends on how clear the language specification is; and how much effort is spend by the people writing the compilers. – GhostCat Apr 10 '15 at 13:54

2 Answers2

0

Compilers usually only check for syntax errors, not semantic errors. And these are semantic errors. The syntax looks fine for both of your codelines. You divide two Integers, and cast an object to another type. Both are valid operations on syntactical level. The actual error is caused by the semantic (cant divide by 0 / the object you try to cast is no instance of a subtype of Person). And consider this code:

class AnObject{
     public AnObject(){
          divide7(0);
     }

     public int divide7(int i){
          return (7 / i);
     }
}

It divides 7 by 0, but if this was a compiletime error, compilers would be horribly inefficient, since they have to inspect the complete code everytime (every single path). And sometimes input is unknown (for example input from a server / the user).

0

The compiler doesn't check for exceptions in the program so often. This is usually because the programmer would know about any exception their program would throw (For example calling an undefined item and getting a thrown NullPointerException/IOException which they should catch to keep the program running)

adsfg
  • 42
  • 1
  • 7