Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perfectly catch the Java NullPointerException in o = objectA.objectB.objectC operation?

Tags:

java

android

Not like C or C++, o = objectA.objectB.objectC will throw a NullPointerException if either object(A, B) is null in Java. In Java 1.7, I can't do anything like lambda expression to run this command with try-catch protection.

So, how will you perfectly cache the exception there?

like image 951
Tommy Avatar asked Apr 20 '26 13:04

Tommy


1 Answers

Sadly there is no sort of "propagate null" operator in Java, although it was talked about some while ago. (The notation o = objectA?.objectB?.objectC was mooted).

In your case you need to check each part in turn:

if (objectA == null){
    o = null;
} else {
   /*OType*/ p = objectA.objectB;
   o = p == null ? null : p.objectC;
}

Using purely the ternary conditional operator is also a possibility, but that means you need to write objectA.objectB in more than one place.

Enclosing the expression around a try catch block seems crude to me as it could smother legitimate NullPointerExceptions if the chain comprises functions (although that is a moot point for direct field access). But it is easy to read, and scales better for long chains:

try {
    o = objectA.objectB.objectC;
} catch (final java.lang.NullPointerException e){
    o = null;
}
like image 57
Bathsheba Avatar answered Apr 23 '26 02:04

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!