Search code examples
javanullpointerexception

Best practise to handle Exception in thread "main" java.lang.NullPointerException from Bean class


Am using Bean class to get/set value for the attributes. In some cases am gettig Exception in thread "main" java.lang.NullPointerException error due to the value is null. What will be the best practice to handle null pointer exception when we get/set values from/to bean class.

Is that ternary operator is good to use or any other suggestions?

Please find the below line of code where am getting null pointer exception.

doc.setCatalog_title(sourceAsMap.get("catalog_title").toString());

Solution

  • The null pointer exception basic cause is that you are calling a method or variable from null variable i.e. a variable which is currently not holding reference of any object. So, the easy way to avoid it is assign that variable a reference 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);