Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is NullPointerException not declared as a checked exception

Tags:

This was the question asked in an interview. NullPointerException is very common; why is it not declared as a checked exception? I googled but did not get a proper answer.

like image 695
giri Avatar asked Apr 21 '10 14:04

giri


People also ask

Is NullPointerException a checked exception?

Answer: NullPointerException is not a checked exception. It is a descendant of RuntimeException and is unchecked.

Is NullPointerException an exception?

NullPointerException is a runtime exception in Java that occurs when a variable is accessed which is not pointing to any object and refers to nothing or null. Since the NullPointerException is a runtime exception, it doesn't need to be caught and handled explicitly in application code.

How do I fix null pointer exceptions?

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.

Is the NullPointerException a compile exception?

NullPointerException is a RuntimeException . Runtime exceptions are critical and cannot be caught at compile time.


1 Answers

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.)

like image 69
Bozho Avatar answered Oct 05 '22 02:10

Bozho