Where does NullPointerException is thrown?

86 views Asked by At

If I'm doing something like this:

String str = null;
str.toLowerCase();

Here I will have a NullPointerException and I want to know where an exception will be created. Does JVM manage such cases and throws NullPointerException or at compile time there are some checks for that case in com.sun.tools.javac.code.Type class?

I can't find a good article which will explain it to me and I also can't find anything related to Runtime exception throwing in OpenJDK javac sources. Can anyone base explanation or link to book\article where I can read about Runtime exceptions creation?

1

There are 1 answers

0
Ankur Anand On BEST ANSWER

Answering this part I want to know where an exception will be created ? or Title itself Where does NullPointerException is thrown?

It's is created on the same call Stack, which is the ordered list of methods that had been called to get to the method where the error occurred which then searches for a method that contains a block of code that can handle the exception (i.e exception handler).

Searching the call stack for the exception handler. Image Source Oracle.

Answering your this part

or at compile time there are some checks for that case ?

No

because A checked exceptions. must be caught somewhere in your code. If not code will not compile. That's why they're called checked exceptions.

Since

String str = null;
str.toLowerCase();

you will be able to compile without handling any Exceptions, so is not a checked exception (You can look for better formal definition on the web).

By now you know that NullPointerException is not a checked exceptions.

Quoting JSL

The unchecked exception classes (ยง11.1.1) are exempted from compile-time checking. i.e all the runtime exceptions

These RuntimeException are thrown when these are detected by the methods because it encountered an error in the virtual machine runtime