How to perfectly capture Java NullPointerException in o = object.object.object operation?
Unlike C or C++, o = objectA.objectB.objectC
will throw a NullPointerException
if object(A, B) is null in Java. In Java 1.7, I can’t do anything like a lambda expression to run a command with try-catch
protection.
So, how would you perfectly cache exceptions there?
Solution
Unfortunately, there is no “propagation null” operator in Java, although it was discussed some time ago. (The symbol o = objectA?. objectB?. objectC
)。
In your case, you need to check each section in turn:
if (objectA == null){
o = null;
} else {
/*OType*/ p = objectA.objectB;
o = p == null ? null : p.objectC;
}
Using purely ternary conditional operators is also possible, but it means that you need to write objectA.objectB
in multiple places.
Including expressions around try
catch
blocks seems crude to me, because if the chain contains functions, it can kill legitimate NullPointerExceptions
(although this is a controversial point for direct field access). But it’s easy to read and scales better for long chains :
try {
o = objectA.objectB.objectC;
} catch (final java.lang.NullPointerException e){
o = null;
}