[Solved] Best practise to handle Exception in thread “main” java.lang.NullPointerException from Bean class [duplicate]


The nullpointer exception basic reason is that you are calling a method or variable from null variable where with null variable I mean a variable which is currently not holding reference of any object. So, the easy way to avoid it is assign that variable a refernce on which subsequent tasks can be called

Now this can be handled in n no. of ways, out of which some basic ways are:

1) Using if condition

if(doc!=null && sourceAsMap!=null && sourceAsMap.get("catalog_title")!=null)
doc.setCatalog_title(sourceAsMap.get("catalog_title").toString());

2) Using ternary operator:

doc = null == doc ? new Document():doc;
doc.setCatalog_title(sourceAsMap!=null && sourceAsMap.get("catalog_title")!=null ? sourceAsMap.get("catalog_title").toString() : null);

Hope that helps

1

solved Best practise to handle Exception in thread “main” java.lang.NullPointerException from Bean class [duplicate]