You should use MetadataUtils.getEncounterType instead which is fail-fast

But bigger problem here is that you fetching data individually for each patient. That slows things down because it means multiple trips to the database. Use Calculations.lastEncounter instead to fetch for all patients in the cohort at the same time.