Explore Courses Blog Tutorials Interview Questions
0 votes
in Java by (3.4k points)

When running this:

public class WhatTheShoot {

    public static void main(String args[]){

        try {

            throw null;

        } catch (Exception e){

            System.out.println(e instanceof NullPointerException);

            System.out.println(e instanceof FileNotFoundException);




The response is:



Which was fairly stunning for me. I would have thought this would net a compile-time error.

Why can I throw null in Java, and why does it upcast it to a NullPointerException?

(Actually, I don't know if it is an "upcast", given I'm throwing null)

Aside from a really really stupid interview question (please nobody ask this in an interview) I cannot see any reason to throw null. Maybe you want to be fired, but that's... I mean, why else would anyone throw null?

Fun fact IntelliJ IDEA 12 tells me that my line, e instanceof NullPointerException, will always be false. Which isn't true at all.

1 Answer

0 votes
by (46k points)

It resembles like it's not that null is used as a NullPointerException, but that the act of striving to throw null itself launches a NullPointerException.

In other words, throw signs that its evidence is nonnull, and if it is null, it throws a NullPointerException.

JLS 14.18 specifies this form:

If the evaluation of the Expression develops frequently, generating a null value, then an occurrence V' of class NullPointerException is generated and thrown rather of null. The throw description then ends abruptly, the idea being a throw with value V'.

Related questions

Browse Categories