NullPointerException
What exactly happens inside the JVM when a NullPointerException is thrown?
When a NullPointerException (NPE) is thrown inside the Java Virtual Machine (JVM), the following steps occur:
1. Instruction Execution in JVM
Common Causes:
2. JVM Bytecode Analysis
The JVM translates Java code into bytecode instructions. For example, the following Java code:
String str = null;
str.length();
compiles to:
aload_1 // Load reference 'str'
invokevirtual // Call method length() on 'str'
3. JVM Throws NullPointerException
Recommended by LinkedIn
Inside the JVM, this happens:
4. Stack Unwinding (Finding a Catch Block)
If an NPE is thrown, the JVM looks for a matching catch block.
Example with Catch Block
public class NPEExample {
public static void main(String[] args) {
try {
String str = null;
str.length(); // Throws NPE
} catch (NullPointerException e) {
System.out.println("Caught NPE: " + e);
}
}
}
5. JVM Prints the Stack Trace (If Uncaught)
If there is no catch block, the JVM terminates the program and prints a stack trace:
Exception in thread "main" java.lang.NullPointerException
at NPEExample.main(NPEExample.java:5)
6. JVM Garbage Collection Consideration
Summary of JVM Process
Excellent article shreya !