To query a single record we have below two approach :
Approach 1. Assign record to a single Account variable as shown below:
Account accountToGet = [SELECT Name From Account where name = 'UniqueAccount' LIMIT 1];
With above line, it throws below error if no record founds : System.QueryException: List has no rows for assignment to SObject
Approach 2. Assign single record to a List variable as mention below :
List<Account> lstAccount = [SELECT Name From Account where name = 'Unknown Account'];
Even if SOQL returns no records, above line doesn't throws an error. We can use below line to avoid NULL errors.
if(!lstAccount.IsEmpty())
System.debug('No Error');
To handle NULL exception in Approach 1, we need to handle NULL exception in try....catch. It looks like an approach where we will error to occur and then handle it in try....catch.
With Approach 2, we can avoid exception to occur and without using try..catch.. also the code will work.
Based on above approaches, I think approach 2 is fine to prevent errors. Can anyone give me suggestion that why should not we use approach 2?