1

I saw one reference for a code in Java which had a line:

throw null;

I tried the same and there is no compilation exception, till now I thought we can only throw exception, I tested that I can throw any number or Object. Why I am not getting compilation exception? If I try to throw String it gives the below exception what does this means?

No exception of type String can be thrown; an exception type must be a subclass of Throwable

Can anyone please explain the reason and use cases where I can use the above code line?

class Solution {
    public int repeatedNTimes(int[] A) {
        for (int i = 0; i < A.length - 1; ++ i) {
            if (A[i] == A[i + 1]) { // any two neighbour numbers 
                return A[i];
            }            
        }
        // could be evenly distributed excluding the above case
        for (int i = 0; i < A.length - 2; ++ i) {
            if (A[i] == A[A.length - 1] || A[i] == A[A.length - 2]) {
                return A[i];
            }
        }
        throw null; // input array is not what has been described
    }
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Sumit Sagar
  • 342
  • 1
  • 6
  • 17
  • 1
    That will crash with an NPE at runtime. I suppose this is allowed because java allows one to use a Throwable *expression* with `throw` – ernest_k Apr 05 '19 at 12:15
  • 2
    Just to clarify _why_ does compiler allow that: `null` is a subclass of every type, that means, including `Throwable`. – Ondra K. Apr 05 '19 at 12:17
  • 2
    null isn't a class, let alone a subclass of every type. – Stultuske Apr 05 '19 at 12:21
  • 1
    To expand on @ernest_k's comment, when you throw, you usually throw an instance of an exception (as in `throw new IllegalStateException();`), not "an exception". It's like asking why you can pass `null` to an ipothetical `void a(Whatever b)` method. It's syntactically valid. As valid as `IllegalStateException e = new IllegalStateException(); throw e;` What if `e` was declared as `IllegalStateException e = null;`? Nothing would change, syntactically. – Federico klez Culloca Apr 05 '19 at 12:35
  • from the original question, And if the ```Expression``` evaluates to ```null```, then a ```NullPointerException``` is thrown. Specifically, ``` 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.``` is this the reason String/Number type exception can't be thrown. As they can't be mapped to ay exception? – Sumit Sagar Apr 05 '19 at 18:22

0 Answers0