java - Why does invoking a method on a null reference compile successfully? -


trying execute piece of code

public class main {     public static void main(string... args) {         new main();     }      main() {         a = null;         a.foo();     } }  class {     void foo() {} } 

i get, obviously, nullpointerexception since has been initialized null. code compiles because (the coder) know variable a can null @ location, while (the compiler)... well, knows too, point warning message

null pointer access: variable can null @ location 

my question is, given both me , know exception going thrown, why code allowed compile? there chance not exception there?

edit:

put in way, why compiler error in someting this

    try {         throw new exception();         int x = 0;     } catch (exception e) {     } 

and not in this

    try {         if(true)throw new exception();         int x = 0;     } catch (exception e) {     } 

put poorly: how compiler discriminates between blocking or not blocking "obvious errors"?

it's allowed compile java language specification not forbid it. knows, want catch nullpointerexception in caller. not best code design, it's allowed jls.

note eclipse compiler can configured display error @ point. default issues warning:

$ java -jar org.eclipse.jdt.core_3.10.2.v20150120-1634.jar -source 1.7 -cp rt.jar main.java ---------- 1. warning in l:\lan\projects\javatest\ecjtest\src\main.java (at line 8)        a.foo();         ^ null pointer access: variable can null @ location ---------- 1 problem (1 warning) 

also static code analyzers findbugs trigger warning on code.

the question why not forbidden jls opinion based. note such feature cannot added now, because may break backwards compatibility. believe, there's existing code may rely on such behavior.


Comments

Popular posts from this blog

php - Zend Framework / Skeleton-Application / Composer install issue -

c# - Better 64-bit byte array hash -

python - PyCharm Type error Message -