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
RangaRayapatiRangaRayapati 

Challenge:Manipulating Records with DML is not accepting below code

I have written below code for in Manipulate Records with DML trailhead CHALLENGE, it not accepting but the output is coming correctly. Can you please guide me what is wrong in it.

Create a method for inserting accounts.
To pass this challenge, create an Apex class that inserts a new account named after an incoming parameter. If the account is successfully inserted, the method should return the account record. If a DML exception occurs, the method should return null.

The Apex class must be called AccountHandler and be in the public scope
The Apex class must have a public static method called insertNewAccount
The method must accept an incoming string as a parameter, which will be used to create the Account name
The method must insert the account into the system and then return the record
The method must also accept an empty string, catch the failed DML and then return null

https://trailhead.salesforce.com/content/learn/modules/apex_database/apex_database_dml

public class AccountHandler {

    public static id insertNewAccount(String AccountName){
        Account acc = new Account(Name = AccountName);
        Database.SaveResult srList = Database.insert(acc, false);
        System.debug('srList :'+srList.getId());
        return srList.getId();
    }
}
Maharajan CMaharajan C
Hi,

If a DML exception occurs, the method should return null - you have to handle this scenario also in code

Try the below code:
 
public class AccountHandler {
    public static Account insertNewAccount (String accName){        
    if(accName!=''){    
        try{
            Account a = new Account(Name=accName);
            insert a;
            return a;
        } catch(Exception e){
            System.Debug('Account not created');
            return null;
        }
    } else {
        return null;
    }
    }    
}

Thanks,
Maharajan.C
RangaRayapatiRangaRayapati
Hi Maharajan,

Thanks for the response!

In my code also it will return null if any exception occurs.

Regards,
Ranga