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
AMRITA AGARWALA 2AMRITA AGARWALA 2 

Why the Trailhead Challenge for Manipulating Records with DML dont pass?

This is my code:
public class AccountHandler {

    public static Account insertNewAccount(String name){
        try{
            Account acc = new Account();
            acc.Name = name ; 
            insert acc ; 
            system.debug(acc.Id);
            return acc;
            
        }catch (DmlException e) {
           System.debug('A DML exception has occurred: ' + e.getMessage());
           return null; 
        }
    }
}
pconpcon
That code shouldn't compile because you do not alway return a value.  You can try
 
public class AccountHandler {
    public static Account insertNewAccount(String name) {
        Account account = new Account(Name = name);
        try {
            insert account;
        } catch (System.DmlException e) {
            return null;
        }
        return account;
    }
}

This way you always return a value since the return is the last line.
Kevin Coyle 17Kevin Coyle 17
Thank you pcon, This worked for me. I had a insert acc.ID and return acc.ID. This kept failing. I get why i didn't need the ID at this point. 
pconpcon
Great.  If you don't mind marking the best answer on this post so that the question is removed from the unanswered queue that would be very helpful.
Ryan ArmstrongRyan Armstrong
pcon, I've been working on this challenge, and keep running into a compile error, so even after pasting your exact code into the Execute Anonymous Window and I still get the error: Only top-level class methods can be declared static

Curious why I'm not able to get this to run.  Any ideas?
pconpcon
You cannot use the code above in the anonymous window.  It has to be saved into a class.  What compliation error are you getting?  The "Only top-level class methods can be declared static"  Can you copy and paste your entire class that you have in the developer console here?

NOTE: When adding code please use the "Add a code sample" button (icon <>) to increase readability and make it easier to reference.
Reddeiah R 3Reddeiah R 3
Thank You Pcon.your great think.
ramesh puthala manohara reddyramesh puthala manohara reddy
Thank you.