Fix undefined method error for NilClass

Add .try to prevent undefined method error for NilClass.