Consider this function :
public boolean foo(){
System.exit(1);
//The lines beyond this will not be read
int bar = 1; //L1
//But the return statement is required for syntactically correct code
return false; //L2
//error here for unreachable code
//int unreachable = 3; //L3
}
Can someone please explain why L1 and L2 visibly not reachable does not give warnings but L3 does.
Because as far as the compiler is concerned,
System.exit()is just another method call.The fact that what it does is end the process can only be found out from the implementation (which is native code, not that it makes any difference).
If you have to put
System.exit()in your code (usually it’s best to avoid it, unless you want to return a code other than 0), it should really be in a method that returnsvoid,main()for example. It’s nicer that way.As for the reachability, the explanation is the same:
returnis a keyword of the Java language, so the compiler or the parser the IDE uses can tell that it’s theoretically impossible for code after thereturnstatement to be executed. These rules are defined here.