This question already has answers here:
Null check chain vs catching NullPointerException
(19 answers)
Check if last getter in method chain is not null
(3 answers)
Closed 5 years ago.
I have an object and i want to check if this object or nested fields are null. I want to print this neted field, but i should check if there is null in some level, otherwise i will get null pointer exception .
I know i can do this:
if( object != null && object.A != null && object.A.B != null && object.A.B.C != null && object.A.B.C.D != null) { doSomething( object.A.B.C.D);}
but its so long. Do you know better way to check it ?
Optional is a good way in Java 8.
String value = foo.getBar().getBaz().toString();
With optional it will be:
String value = Optional.ofNullable(foo)
.map(Foo::getBar)
.map(Bar::getBaz)
.map(Baz::toString)
.orElse("EmptyString");
You could implement an interface on all objects with method that returns all child objects and create a method that calls itself recursively to verify that all objects are set.
Let assume that this is a check to prevent misuse of a method, so this should not occurs too many time.
Simply catch this exception, this will invalidate the value.
private boolean isValid(YourObject object){
try{
return object.A.B.C.D != null;
} catch (NullPointerException npe){
return false;
}
}
Of course, don't use this solution if you are doing a lot of validation and those return false to often, exception are an heavy process.
EDIT :
As Fildor point it out, there is a cost to use a try-catch even without exception. But using this answer I can assume this will be limited and there is not much optimization to do on this unique line.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
This post was edited and submitted for review 12 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I'm working on nested exceptions in java, I wanted to check the type of my custom exception using the condition (eg. if(t.getCause().getCause() instanceOf MyCustomException)) but this might throw a potential NPE.
So I'm planned to check for null using below condition
if((t.getCause().getCause() != null) && (t.getCause().getCause() instanceOf MyCustomException)) {
..........
}
Is it a good approach, Any suggestions would be appreciated?
Thanks!
Your approach would not work the way you're planning. Let me explain why:
When you use instanceof you are already checking if an object is null (e.g. null is not instanceof myCustomerException, so it is false)
If you are already using instanceof it means your problem is not in t.getCause().getCause(), but might be with t.getCause() or even t.
I would suggest you have a method to do the check for you, so you do a clean call. Something like:
public boolean isTheNestedException(Throwable t) { // Assuming you are using throwable
return t != null && t.getCause() != null && t.getCause().getCause() instanceof MyCustomerException; // Assuming your "MyCustomerException" is a custom exception class
}
You would use it like:
if (isTheNestedException(t) {
....
}
instanceOf does not cause NullPointerException.
JLS 15.20.2. Type Comparison Operator instanceof says:
the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false.
Now, the first getCause() can return null, making the second call cause NPE, so your code should be:
if (t.getCause() != null
&& t.getCause().getCause() instanceOf myCustomeException) {
..........
}
This presumes that t itself cannot be null.
Your proposed code is fragile. If you ever change the nesting, the if will break. A better pattern is to write a general purpose search on causal chains:
#SuppressWarning("unchecked")
public static <T> T getFirstCause(Throwable ex, Class<T> exClass) {
for (Throwable cause = ex; cause != null; cause = cause.getCause()) {
if (exClass.isAssignableFrom(cause)) {
// Unchecked by Java type system, but verified by the if above.
return (T) cause;
}
}
return null;
}
Now you say
if (getFirstCause(t, myCustomeException.class) != null) {
...
}
You can also retrieve the matching instance if needed.
myCustomeException customEx = getFirstCause(t, myCustomeException.class);
if (customEx != null) {
OtherInfo info = customEx.getCustomeExInfo()
}
One if the best ways I've seen is something like
Throwable anException = t.getCause();
while(anException != null){
// Do a thing with with the throwable.
anException = anException.getCause();
}
I didn't test it, but you should get the idea!
This question already has answers here:
Null check chain vs catching NullPointerException
(19 answers)
Closed 6 years ago.
I have a complex model structure in my project.
Sometimes I have to get a deep placed value from it. It looks like following:
something.getSomethongElse().getSecondSomething().getThirdSomething().getFourthSomething();
The problem is that each of those methods could return null, and I will get NullPointerException in case if it does.
What I want to know is should I write long if like
if(something != null && something.getSomethongElse() != null && something..getSomethongElse().getSecondSomething() != null && something.getSomethongElse().getSecondSomething().getThirdSomething() != null && omething.getSomethongElse().getSecondSomething().getThirdSomething().getFourthSomething() != null) {
//process getFourthSomething result.
}
Or it is OK just to use try..catch like following:
SomethingFourth fourth = null;
try {
fourth = something.getSomethongElse().getSecondSomething().getThirdSomething().getFourthSomething();
} catch (NullPointerException e) { }
if(fourth != null) {
///work with fourth
}
I know that NPE is a thing to be avoided, but isn't it overhead to avoid it in my case?
If you can refactor the code and make each method return Optional. It will be possible to avoid null checks and try ... catch.
Optional<Result> result = something.getSomethingElse()
.flatMap(e -> e.getSecondSomething())
.flatMap(x -> x.getThirdSomething())
.flatMap(e -> e.getFourthSomething());
// at the end to check if result is present
result.ifPresent(..some_logic_here..); // or result.orElse(...);
so getSomethingElse() returns Optional<SomethingElse>, getThirdSomething() - Optional<ThirdSomething> and so on. We have to use here flatMap(Function<? super T,Optional<U>> mapper) because if the provided mapper is one whose result is already an Optional, and if invoked, flatMap does not wrap it with an additional Optional. In other words if map on map(e -> e.getSecondSomething()) the result type will be Optional<Optional<SecondSomething>> and we will have to do unnecessary get() call - map(...).get().map(...).
I hope this helps.
UPDATED
You can do the same thing using method references.
Optional<Result> result = something.getSomethongElse()
.flatMap(SomethongElse::getSecondSomething)
.flatMap(SecondSomething::getThirdSomething)
.flatMap(ThirdSomething::getFourthSomething);
Before calling a function of an object, I need to check if the object is null, to avoid throwing a NullPointerException.
What is the best way to go about this? I've considered these methods.
Which one is the best programming practice for Java?
// Method 1
if (foo != null) {
if (foo.bar()) {
etc...
}
}
// Method 2
if (foo != null ? foo.bar() : false) {
etc...
}
// Method 3
try {
if (foo.bar()) {
etc...
}
} catch (NullPointerException e) {
}
// Method 4 -- Would this work, or would it still call foo.bar()?
if (foo != null && foo.bar()) {
etc...
}
Method 4 is best.
if(foo != null && foo.bar()) {
someStuff();
}
will use short-circuit evaluation, meaning it ends if the first condition of a logical AND is false.
The last and the best one. i.e LOGICAL AND
if (foo != null && foo.bar()) {
etc...
}
Because in logical &&
it is not necessary to know what the right hand side is, the result must be false
Prefer to read :Java logical operator short-circuiting
Since java 8 you can use Objects.nonNull(Object obj)
if(nonNull(foo)){
//
}
Do not catch NullPointerException. That is a bad practice. It is better to ensure that the value is not null.
Method #4 will work for you. It will not evaluate the second condition, because Java has short-circuiting (i.e., subsequent conditions will not be evaluated if they do not change the end-result of the boolean expression). In this case, if the first expression of a logical AND evaluates to false, subsequent expressions do not need to be evaluated.
Method 4 is far and away the best as it clearly indicates what will happen and uses the minimum of code.
Method 3 is just wrong on every level. You know the item may be null so it's not an exceptional situation it's something you should check for.
Method 2 is just making it more complicated than it needs to be.
Method 1 is just method 4 with an extra line of code.
In Java 7, you can use Objects.requireNonNull().
Add an import of Objects class from java.util.
public class FooClass {
//...
public void acceptFoo(Foo obj) {
//If obj is null, NPE is thrown
Objects.requireNonNull(obj).bar(); //or better requireNonNull(obj, "obj is null");
}
//...
}
As others have said #4 is the best method when not using a library method. However you should always put null on the left side of the comparison to ensure you don't accidentally assign null to foo in case of typo. In that case the compiler will catch the mistake.
// You meant to do this
if(foo != null){
// But you made a typo like this which will always evaluate to true
if(foo = null)
// Do the comparison in this way
if(null != foo)
// So if you make the mistake in this way the compiler will catch it
if(null = foo){
// obviously the typo is less obvious when doing an equality comparison but it's a good habit either way
if(foo == null){
if(foo = null){
I would say method 4 is the most general idiom from the code that I've looked at. But this always feels a bit smelly to me. It assumes foo == null is the same as foo.bar() == false.
That doesn't always feel right to me.
Method 4 is my preferred method. The short circuit of the && operator makes the code the most readable. Method 3, Catching NullPointerException, is frowned upon most of the time when a simple null check would suffice.
Simple one line Code to check for null :
namVar == null ? codTdoForNul() : codTdoForFul();
Update
I created a java library(Maven Dependency) for the java developers to remove this NullPointerException Hell from their code.
Check out my repository.
NullUtil Repository
Generic Method to handle Null Values in Java
<script src="https://gist.github.com/rcvaram/f1a1b89193baa1de39121386d5f865bc.js"></script>
If that object is not null we are going to do the following things.
a. We can mutate the object (I)
b. We can return something(O) as output instead of mutating the object (I)
c. we can do both
In this case, We need to pass a function which needs to take the input param(I) which is our object If we take it like that, then we can mutate that object if we want. and also that function may be something (O).
If an object is null then we are going to do the following things
a. We may throw an exception in a customized way
b. We may return something.
In this case, the object is null so we need to supply the value or we may need to throw an exception.
I take two examples.
If I want to execute trim in a String then that string should not be null. In that case, we have to additionally check the null value otherwise we will get NullPointerException
public String trimValue(String s){
return s == null ? null : s.trim();
}
Another function which I want to set a new value to object if that object is not null otherwise I want to throw a runtime exception.
public void setTeacherAge(Teacher teacher, int age){
if (teacher != null){
teacher.setAge(age);
} else{
throw new RuntimeException("teacher is null")
}
}
With my Explanation, I have created a generic method that takes the value(value may be null), a function that will execute if the object is not null and another supplier function that will execute if the object is null.
GenericFunction
public <I, O> O setNullCheckExecutor(I value, Function<I, O> nonNullExecutor, Supplier<O> nullExecutor) {
return value != null ? nonNullExecutor.apply(value) : nullExecutor.get();
}
So after having this generic function, we can do as follow for the example methods
1.
//To Trim a value
String trimmedValue = setNullCheckExecutor(value, String::trim, () -> null);
Here, the nonNullExecutor Function is trim the value (Method Reference is used). nullExecutorFunction is will return null since It is an identity function.
2.
// mutate the object if not null otherwise throw a custom message runtime exception instead of NullPointerException
setNullCheckExecutor(teacher, teacher -> {
teacher.setAge(19);
return null;
}, () -> {
throw new RuntimeException("Teacher is null");
});
Correction: This is only true for C/C++ not for Java, sorry.
If at all you going to check with double equal "==" then check null with object ref like
if(null == obj)
instead of
if(obj == null)
because if you mistype single equal if(obj = null) it will return true (assigning object returns success (which is 'true' in value).
You also can use ObjectUtils.isNotEmpty() to check if an Object is not empty and not null.
If you control the API being called, consider using Guava's Optional class
More info here. Change your method to return an Optional<Boolean> instead of a Boolean.
This informs the calling code that it must account for the possibility of null, by calling one of the handy methods in Optional
if you do not have an access to the commons apache library, the following probably will work ok
if(null != foo && foo.bar()) {
//do something
}
Your last proposal is the best.
if (foo != null && foo.bar()) {
etc...
}
Because:
It is easier to read.
It is safe : foo.bar() will never be executed if foo == null.
It prevents from bad practice such as catching NullPointerExceptions (most of the time due to a bug in your code)
It should execute as fast or even faster than other methods (even though I think it should be almost impossible to notice it).
We can use Object.requireNonNull static method of Object class. Implementation is below
public void someMethod(SomeClass obj) {
Objects.requireNonNull(obj, "Validation error, obj cannot be null");
}
public <T, U> U defaultGet(T supplier, Function<T, U> mapper, U defaultValue) {
return Optional.ofNullable(supplier).map(mapper).orElse(defaultValue);
}
You can create this function if you prefer function programming
Allot of times I look for null when processing a function -
public static void doSomething(Object nullOrNestedObject) {
if (nullOrNestedObject == null || nullOrNestedObject.getNestedObject()) {
log.warn("Invalid argument !" );
return;
// Or throw an exception
// throw new IllegalArgumentException("Invalid argument!");
}
nullOrNestedObject.getNestedObject().process()
... // Do other function stuff
}
That way if it is null it just stops execution early, and you don't have to nest all of your logic in an if.
Here is a simple code snippet and I cannot figure out why does it throw a NullPointerException.
String lastGroup = "";
menuTevekenysegekGrouped = new ArrayList<MenuElem>();
for(MenuElem me : menuA) {
// double checked that me objects are never null
// double checked that menuA is never null
if(me.getGroup() != null && !me.getGroup().equals(lastGroup)) { /* NPE!!! */
lastGroup = me.getGroup();
MenuElem separ = new MenuElem();
separ.setCaption(lastGroup);
separ.setGroupHead(true);
menuTevekenysegekGrouped.add(separ);
menuTevekenysegekGrouped.add(me);
} else {
menuTevekenysegekGrouped.add(me);
}
}
In the first iteration the me.getGroup() returns null. So the first operand of the && is false and second operand should not evaluate according to the JLS, as far as I know. However when I debug the code I get NPE from the marked line. I'd like to know why. (Using JRockit 1.6.0_05 if it matters..)
Are you sure that me itself is not, in fact, null?
From your code (without the stacktrace I have to guess), the following may be null and be the cause: menuA or me or menuTevekenysegekGrouped. And some of the values returned from the methods/or used in the methods may also be null, but it's hard to know...
If me is not null, then the only other object that can be null in the above snippet is menuTevekenysegekGrouped. Add a check before first using it to ensure that it's not null.
The repeated calls to me.getGroup() would bug me enough to pull them out into a local variable:
String lastGroup = "";
for(MenuElem me : menuA) {
String thisGroup = me.getGroup();
if(thisGroup != null && !thisGroup.equals(lastGroup)) {
lastGroup = thisGroup;
MenuElem separ = new MenuElem();
separ.setCaption(lastGroup);
separ.setGroupHead(true);
menuTevekenysegekGrouped.add(separ);
menuTevekenysegekGrouped.add(me);
} else {
menuTevekenysegekGrouped.add(me);
}
}
This is only going to fix your problem if in fact me.getGroup() returns different values (sometimes null) on multiple calls with the same me, but it might make it easier to debug, and certainly makes it easier to read.