Hi This was the question asked in interview, null pointer exception is very common why it is not declared as checked exception.I googled but did not get proper answer.
Thanks
Hi This was the question asked in interview, null pointer exception is very common why it is not declared as checked exception.I googled but did not get proper answer.
Thanks
Almost every method would have to declare throwing it.
public void myMethod(String param) throws NullPointerException {
//
}
(As a sidenote - Eclipse for example gives you a warning whenever there is a "potential null pointer access" so that you can prevent the exception as early as possible.)
Null pointer exceptions are extensions of Runtime exceptions and are therefore unexpected occurances in your program flow. It wouldn't make sense to expect a null pointer exception to be thrown (I hope!) and therefore you would never declare it as a checked exception.
It's not a checked exception (among other things) because it is extremely common. It can occur pretty much everywhere. If it were checked, then nearly every single method in every single Java program anywhere would have to declare that it throws NullPointerException
.
The one sentence answer I would give is that it is the result of a programming error, and programming error exceptions are not checked exceptions (IllegalStateException, ClassCastException, etc.).
But even if you had an argument for why it should maybe be a checked exception, basically every operation on an object reference can throw it, so it would be all over the place and literally every method in a non-trivial program would have to throw it - so what would be the point?
My own obligatory definition for checked Exception. Checked exceptions are exceptions that an API would raise in-case of a known undesirable situation arises
NullPointerException
s does not indicate a "known undesirable" situation. Instead, those are generally thrown due to some unhanded situations in the code. That is, they are most of the time due to bad coding practices - Such as trying get size of a list which is not initialized properly etc. So, there is no point in making them checked exceptions - as every object in Java could be null at some point?!. NullPoitnerException`s never should be caught either.
Checked exceptions can occur because something in the environment, over which your program has little or no control, went wrong (e.g. IOException
, SQLException
). You can anticipate that and handle that case.
A NullPointerException
(usually) occurs because there is some bug in your code. If you expect a NullPointerException to be thrown, the correct solution is to fix the bug rather than to handle the exception.