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:
true false
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.
null can be cast to anything*, including an Exception. Just as you could return null if your method signature specifies you should return an Exception (or indeed a string, or Person class), you can throw it.
In Java, the java. lang. NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.
You can't throw two exceptions. I.e. you can't do something like: try { throw new IllegalArgumentException(), new NullPointerException(); } catch (IllegalArgumentException iae) { // ... }
Throwing an exception is as simple as using the "throw" statement. You then specify the Exception object you wish to throw. Every Exception includes a message which is a human-readable error description. It can often be related to problems with user input, server, backend, etc.
It looks like it's not that null
is treated as a NullPointerException
, but that the act of attempting to throw null
itself throws a NullPointerException
.
In other words, throw
checks that its argument is nonnull, and if it is null, it throws a NullPointerException
.
JLS 14.18 specifies this behavior:
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'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With