function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
davecrusodavecruso 

Try / Catch on Constructor - How to get this working?

Hi all, 

 

We're trying to troubleshoot an issue with the constructor query, and would love to get a try/catch working with it. We're getting a List error (out of bounds) sometimes, but can't seem to replicate regularly...

 

Any suggestions about how to get a try/catch working? Maybe call a method (not sure how this would look)?

 

Here's our code:

 

 

public CT_ApplicationPage6() { PageReference pageRef = System.currentPageReference(); string x = pageRef.getParameters().get('id'); List <CT_Application__c> cta = [Select Contact__r.firstname, Region__r.Name,Region__r.Volunteer_Manager__r.firstname, Region__r.Volunteer_Manager__r.lastname,Region__r.Volunteer_Manager__r.email From CT_Application__c where Contact__c=:x order by createddate desc]; setconid(cta[0].id); setconfName(cta[0].Contact__r.firstname); setregion(cta[0].Region__r.Name); setvmemail(cta[0].Region__r.Volunteer_Manager__r.email); setvmName(cta[0].Region__r.Volunteer_Manager__r.firstname + ' ' + cta[0].Region__r.Volunteer_Manager__r.lastname); //get trainnig date List <Training_Registration__c> tr = [SELECT Location__c,Training_Date__r.Training_Date__c FROM Training_Registration__c where Contact__c=:x]; List <String> td = String.valueOF(tr[0].Training_Date__r.Training_Date__c).split('-'); setTrnDate(td[1] + '-' + td[2] + '-' + td[0]); }

 

 Try / Catch Code: 

 

 

catch(exception ex) { PageReference errorPage = Page.Exception; errorPage.getParameters().Put('error',ex.getMessage()); return errorPage; }

 

Thanks for your suggestions and thoughts!

 

--Dave 

 

 

 

XactiumBenXactiumBen

You don't really need a try / catch on here.

 

All you need to do is check the size of your lists after you have queried your objects.

 

For example:

 

List<MyObject__c> myList = new List<MyObject__c>([Select Id, Name From MyObject__c]); if (myList.size() == 1) { // do my logic here String myName = myList.get(0).Name; }

Failure to add the if statement in red when the MyObject__c query retrieves no records will result in a list index out of bounds error.

davecrusodavecruso

Right -- that's a solid idea (can implement) but it doesn't help us identify what's going wrong earlier, and the cases when the lists are empty (because theoretically, they should always populate)... 

 

--Dave 

XactiumBenXactiumBen

I must have misunderstood the question the first time.  You should be able to put debug statements inside your catch code - these should show up in the System Log if it gets there:

 

catch (Exception e) { System.debug('Check my variables here');

return; }