Monday, June 23, 2008

Something new about null values

Alex blogged about weird code snipped found by our colleague Tim Eck:


public class Weird {
public static void main(String[] args) {
throw null;
}
}


Apparently it compiles, and expectedly throws an NPE at runtime. So, why does it compiles if throw statement accepts only subtypes of Throwable and null is not instance of Throwable? The JLS specification states that "The null reference can always be cast to any reference type", but then in above example compiler does not require main method to throw throwable. Weird, eh?




Update: The answer is of course in the Java Language Specification:


"A throw statement first evaluates the Expression. If the evaluation of the Expression completes abruptly for some reason, then the throw completes abruptly for that reason. If evaluation of the Expression completes normally, producing a non-null value V, then the throw statement completes abruptly, the reason being a throw with value V. If evaluation of the Expression completes normally, producing a null value, then an instance V' of class NullPointerException is created and thrown instead of null. The throw statement then completes abruptly, the reason being a throw with value V'."

No comments:

Post a Comment