2

I have below Apex class (DAO class) which has a try-catch block. Same try-catch block has been used in 5 different methods. I tried sending setOpportunityId as account id or null id but still, it is not going to catch block.

Class:

public with sharing class OppUpdateDAO {
public static List<Opportunity> getOpportunityData(set<ID> setOpportunityId) {
        try {
            List<Opportunity> opportunityList = new List<Opportunity>();
            opportunityList=[select id , name, stageName,RecordTypeId ,Market__cfrom Opportunity where id in:setOpportunityId ];
            return opportunityList;

        }
        catch (Exception e) {
            Error_Handling__c error = M2O_ErrorHandling.errorHandling (e);
            insert error;
            return null;
        }
    }
}
1
  • 2
    As an aside, your method could just have a single line of code inside the code block: public static Opportunity[] getOpportunityData(set<ID> setOpportunityId) { return [select name, stageName, RecordTypeId, Market__c from Opportunity where id in :setOpportunityId ]; }
    – sfdcfox
    Oct 30, 2018 at 22:12

1 Answer 1

3

Lets analyse the code in your try block.

List<Opportunity> opportunityList = new List<Opportunity>();
opportunityList=[select id , name, stageName,RecordTypeId ,Market__cfrom Opportunity where id in:setOpportunityId ];
return opportunityList;

There is no way there can be an catchable exception that can appear in those 3 lines.

The only exception that can occur is Heap or Too many SOQL exceptions which is Limit exception that cannot be caught so catch block is useless.

Theriotically catch block will never be called, and thus I dont think you need a try catch block in the first place.

Solution : Remove the try catch.

3
  • not a QueryException 'Record Not Available' due to a long-held lock by some other transaction?
    – cropredy
    Oct 31, 2018 at 4:18
  • @cropredy thats a great shout, I am the dilemma if the try catch should be written for it. That being said I never reproduced in test execution so i wonder how to cover it without test.IsRunningTest Oct 31, 2018 at 10:28
  • 1
    Pranay: Well, the way to cover it without using Test.isRunningTest is to use Selector classes and ApexMocks doThrowWhen. But as sfdcfox so often says, for self-evident catch blocks of unusual exceptions, “why bother”.
    – cropredy
    Oct 31, 2018 at 13:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .