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
SS KarthickSS Karthick 

Database Methods in Try Catch

Hi Everybody,
         Can anyone tell me how to use Database methods in try catch block ??
Please Give some example


Thanks in advance
Karthick
Best Answer chosen by SS Karthick
Sonam_SFDCSonam_SFDC
You should use Database.saveresult when using try and catch:

sample:

try
    {
           Database.SaveResult[] srList = Database.insert(lstMix, false);
    }
    catch( DmlException ex )
    {
            // fail gracefully
    }

// Iterate through each returned result
for (Database.SaveResult sr : srList) {
    if (sr.isSuccess()) {
        // Operation was successful, so get the ID of the record that was processed
        System.debug('Successfully updated Mix ' + sr.getId());
    }
    else {
        // Operation failed, so get all errors               
        for(Database.Error err : sr.getErrors())
        {
            System.debug('The following error has occurred.');                   
            System.debug(err.getStatusCode() + ': ' + err.getMessage());
            System.debug('Mix that affected this error: ' + err.getFields());
        }
            
    }
    }

All Answers

Sonam_SFDCSonam_SFDC
You should use Database.saveresult when using try and catch:

sample:

try
    {
           Database.SaveResult[] srList = Database.insert(lstMix, false);
    }
    catch( DmlException ex )
    {
            // fail gracefully
    }

// Iterate through each returned result
for (Database.SaveResult sr : srList) {
    if (sr.isSuccess()) {
        // Operation was successful, so get the ID of the record that was processed
        System.debug('Successfully updated Mix ' + sr.getId());
    }
    else {
        // Operation failed, so get all errors               
        for(Database.Error err : sr.getErrors())
        {
            System.debug('The following error has occurred.');                   
            System.debug(err.getStatusCode() + ': ' + err.getMessage());
            System.debug('Mix that affected this error: ' + err.getFields());
        }
            
    }
    }
This was selected as the best answer
USHA R 5USHA R 5
Hi Sonam,

I am having an apex class in above format with Database.saveResult.
I am facing issue in writing test class. Couldn't able to cover the else part and make isSuccess as false.

Can you please help in this context?