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
Vijay Kumar Rebbala 1Vijay Kumar Rebbala 1 

How to Escape from Query Exception??

How to escape the exception if there are no results from Soql Query and do I hit any Governer Limits by looking at the code??

global class DeleteoldCases{
    Public void DeleteoldCases(){
        List<Case> QueryCases = [SELECT Id FROM Case WHERE Case.CreatedDate < LAST_N_MONTHS:18 ORDER BY CreatedDate ASC  LIMIT 9000];
        If (QueryCases == null){return;}
        system.debug('********List of Cases********'+QueryCases);
        try{
            delete QueryCases;
        }catch(DmlException e) {
            System.debug('An unexpected error has occurred: ' + e.getMessage());
        }  
    }
}
Best Answer chosen by Vijay Kumar Rebbala 1
Vivek DeshmaneVivek Deshmane
Hi,
your code and query looks good and will not hit any limit, i have just added not empty check.
global class DeleteoldCases{
    Public void DeleteoldCases(){
        List<Case> QueryCases = [SELECT Id FROM Case WHERE Case.CreatedDate < LAST_N_MONTHS:18 ORDER BY CreatedDate ASC  LIMIT 9000];
        If (QueryCases == null || (QueryCases!=null && !QueryCases.isEmpty()))
		{
		 return;
		}
        
        try{
            delete QueryCases;
        }catch(DmlException e) {
            System.debug('An unexpected error has occurred: ' + e.getMessage());
        }  
    }
}

Please let me know if this helps you

Best Regards,
-Vivek

All Answers

Vivek DeshmaneVivek Deshmane
Hi,
your code and query looks good and will not hit any limit, i have just added not empty check.
global class DeleteoldCases{
    Public void DeleteoldCases(){
        List<Case> QueryCases = [SELECT Id FROM Case WHERE Case.CreatedDate < LAST_N_MONTHS:18 ORDER BY CreatedDate ASC  LIMIT 9000];
        If (QueryCases == null || (QueryCases!=null && !QueryCases.isEmpty()))
		{
		 return;
		}
        
        try{
            delete QueryCases;
        }catch(DmlException e) {
            System.debug('An unexpected error has occurred: ' + e.getMessage());
        }  
    }
}

Please let me know if this helps you

Best Regards,
-Vivek
This was selected as the best answer
Vijay Kumar Rebbala 1Vijay Kumar Rebbala 1
I didn't get this change '(QueryCases!=null && !QueryCases.isEmpty())'. What is the need of this??
Vivek DeshmaneVivek Deshmane
Hi,
If criteria will not met then query will retunr 0 rows hence I have added empty check

Best Regards,
-Vivek
Vijay Kumar Rebbala 1Vijay Kumar Rebbala 1
QueryCases!=null, how does that help in empty check??