0

I am using a StandardSetController with Database.getQueryLocator to call my query. I am wondering what can go wrong in this code snippet, i.e. what is the Exception that has a probability of being thrown? It does not throw exception when there is no data. If I wrap it in a try catch block, apart from the generic "Exception", what other catch blocks do I write for more specific Exceptions?

setCon = new ApexPages.StandardSetController(
                                    Database.getQueryLocator(
                                        [SELECT Id, Name, 
                                            (SELECT Id, CaseNumber, Subject, Contact.Name, IsClosed, Reason 
                                                FROM Cases) 
                                            FROM Account 
                                            WHERE BillingCity = :account.BillingCity
                                            AND Industry = :account.Industry
                                        ]
                                    ));
  • I can't see why that would ever throw an exception, what makes you think it would? – Phil Hawthorn Jul 8 '17 at 9:53
  • It might throw an error, when account is null, because you have account.BillingCity and account.Industry, so you better put a condition to check if account!= null – Nitish Singhal Jul 8 '17 at 10:53
4

There is no need for a try-catch block your code, because there is nothing you can catch that's worth catching. There's governor limits that could be exceeded, which you can't catch, and the exceptions that could be thrown can be avoided with some minor modifications to the code.

NullPointerException

If account is null, you'll get this. Just make sure your variable is initialized, and you won't have to worry about catching this.

LimitException

If there's more than 10,000 records, you'll get this. Consider adding LIMIT 10000.

SObjectException

If your account comes from a query, and BillingCity/Industry is not selected, you can get this exception. Make sure that those fields are present (but may be null).

  • Thanks a lot!!! @sfdcfox for your totally awesome answer. Helped me a lot. Yes my account object is initialized properly elsewhere so NullPointerException will never happen. The scenario you gave for SObjectException will also not occur for my code. I will add the LIMIT 10000 right away! – SFDC Dev 27 Jul 9 '17 at 4:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.