Check the object is null or enclose with try and catch
sol1: if(mainObject && mainObject.yourObject != null { /** add what yuo what you want to handle*/ }
if(mainObject && mainObject.yourObject != null { /** add what yuo what you want to handle*/ }
Sol2: try{obj = mainObject.yourObject;}catch(Exception e){/** fallback code*/}
try{obj = mainObject.yourObject;}catch(Exception e){/** fallback code*/}