Activity Forums Salesforce® Discussions System.Query Exception

  • Parul

    Member
    August 30, 2018 at 12:03 pm

    Hello Chanchal,

    The exception is because of you are not getting any record in your SOQL query..

    which meet the where criteria so it's give error.

    Thanks.

    Parul

    • This reply was modified 5 years, 8 months ago by  Parul.
  • shariq

    Member
    September 14, 2018 at 10:24 pm

    Hi,

    Any error related to query will give this exception.

    for example:-

    1. String not correctly setup in dynamic query - 'select id from contact where id = 'testId''

    How to handle it-

    When attempting to fetch a single record from the database it is easy to run into the above exception. I’ve seen two schools of thought in dealing with this issue – mostly in the forums – and have been hoping to find a more official standpoint.

    I’ll describe the patterns and perhaps you can help me decide.

    The Try-Catch Pattern

    Surround your query by a try-catch block.
    Fetch the record into a single object type variable.
    Either the query successfully executes, or the exception is caught and you deal with it appropriately.
    An example,

    MyObject__c obj;

    try{

    obj = [SELECT id FROM MyObject__c WHERE name=:previouslyDefinedVar];

    } catch(System.QueryException e){

    // Perform logic here

    }
    The Only Use Lists For Query Results Pattern

    Fetch records into Lists of objects. Do this even if you only expect a single row to be returned. [Queries that return values into Lists do not throw the above exception]
    Check the size of the list(perhaps with an if-statement) and only perform required actions on the record if the list has a size of 1.
    List<MyObject__c> objects = [SELECT id FROM MyObject__c WHERE name=:previouslyDefinedVar];

    if(objects.size()==1){

    // Perform Logic

    }

    Hope this helps.

     

     

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos