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
Arun ChaubeyArun Chaubey 

Create a method for inserting accounts

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 'insertNewAccount' method must accept an incoming string as a parameter, name the account after the parameter, insert it into the system and then return the account record.
The 'insertNewAccount' method must also accept an empty string, catch the failed DML and return null.
Best Answer chosen by Arun Chaubey
NagaNaga (Salesforce Developers) 
Hi Arun,

Can you please let me know if the code below helps you


public class AccountHandler {
public static Account insertNewAccount(String name) {
Account a = new Account();
a.Name = name;
try
{
insert a;
} catch (Exception e) {
return null;
}
return a;
}
}
This method takes name string parameter and makes a new Account. Then it tries to insert it, but if insert fails then it returns null. If insert succeeds, it will return that account object.

Best Regards
Naga Kiran
 

All Answers

NagaNaga (Salesforce Developers) 
Hi Arun,

Can you please let me know if the code below helps you


public class AccountHandler {
public static Account insertNewAccount(String name) {
Account a = new Account();
a.Name = name;
try
{
insert a;
} catch (Exception e) {
return null;
}
return a;
}
}
This method takes name string parameter and makes a new Account. Then it tries to insert it, but if insert fails then it returns null. If insert succeeds, it will return that account object.

Best Regards
Naga Kiran
 
This was selected as the best answer
Arun ChaubeyArun Chaubey
Hi Naga,

Thank you very much. It is working fine. I was stuck with the last part. Thank You once again.
Jean-Christophe LEGEAYJean-Christophe LEGEAY
You could also create the new account directly with the string given in parameter :

public static Account insertNewAccount (string nom){            
     
        Account NewAccount = new Account(Name = nom);
Srinivas KoduruSrinivas Koduru
I think follwoing is what is just fine I think.

public class AccountHandler {

    public static Account insertNewAccount(String actName){
        Account act = new Account(Name=actName);
        try{
            insert act;
            return act;
        }catch(DMLException e){
            system.debug('DML Exception: ' + e);
            return null;
        }
    }
}

Check if this is working fine or not by using the following code in your Execute Anonymous Window
Satyanarayana PusuluriSatyanarayana Pusuluri
Hi,

Below code working fine for this Challenge 

public class AccountHandler {
    public static Account insertNewAccount(String name) {
        Account Acct = new Account();
        Acct.Name = name;
        try
        {
            insert Acct;
        } catch (Exception e) {
            return null;
        }
        return Acct;
    }
}

Thanks & Regards,
Satya P
Kishan MalepuKishan Malepu
public class AccountHandler {
        public static account insertNewAccount(String Name)
        {    
            Account acc = new Account();
            acc.Name  = Name;
            try{
                insert acc;
             }
            catch(DMLException e)
            {
                System.debug('A DML exception has occurred: ' + e.getMessage());
                return null;
            }
            return acc;
        }
 
}
Yazz_KYazz_K
You guys are awesome. Any recommendations on, let's say, a crash-course with Apex?
hutch doghutch dog
what to write in the apex code window for this task?
Muhammad AlaaMuhammad Alaa
Here is what I did:
 
public class AccountHandler {
    public static Account insertNewAccount(String accntName) {
        try{
            Account acct = new Account();
        	acct.Name = accntName;
        	insert acct;
			return acct;
        }catch(DmlException e){
            return null;
        }
    }
}

IMHO, the compiler has issues with Finally in TryCatch blocks, in general
Rahul Gupta 137Rahul Gupta 137
User-added image

why such error ?
Julie NJulie N
Rahul : line 5 you want the variable you've defined at line 2, so just put on line 5 :

acct.Name = Name;

I think it'll be ok then ;) 
 
Mayank shahMayank shah
public class AccountHandler {
    public static Account insertNewAccount(string Test){
       
        Account acct = new Account();
        acct.Name = Test;
         try{
        insert acct;
        }
        Catch(Exception e){
            System.debug ('An Error has occoured'+e.getMessage());
            return null;
        }
            return acct;
    }
}
Ben RowleyBen Rowley
public class AccountHandler {

    public static Account insertNewAccount(String accName){
        
        Account acc = new Account(Name=accName, Phone='(415)555-1212', NumberOfEmployees=100);
        
        Database.SaveResult sr = Database.insert(acc, false);

           if (sr.isSuccess()) {
        // Operation was successful, return
               return acc;
           } 
        else {
            //what was the error?
            for(Database.Error err : sr.getErrors()) {
                System.debug('The following error has occurred.');
                       System.debug(err.getStatusCode() + ': ' + err.getMessage());  
         }
    }
       //then return null 
       return null;

        }
    }
Loic MesseguerLoic Messeguer
For anyone getting this error : " Challenge Not yet complete... here's what's wrong: 
There was an unexpected error in your org which is preventing this assessment check from completing: System.NullPointerException: Attempt to de-reference a null object "
Try going into your Object "Account" and deactivate any Validation Rules that you have running.
Hope I helped someone.
Absolute NoobAbsolute Noob
Hi, Seeking help to solve this error.  
ERROR : There was an unexpected error in your org which is preventing this assessment check from completing: System.DmlException: Delete failed. First exception on row 0 with id 0011U000009QL8LQAW; first error: DELETE_FAILED, Your attempt to delete My Test Account could not be completed because it is associated with the following cases.: 00001030 : []

Code I wrote:
 

public class AccountHandler {
    
    public static Account insertNewAccount(String nameishello)
    {
        Account act = new Account();
        act.Name = nameishello;
        
        try{ 
            insert act;
        }
        catch(Exception e) 
        {
            return null; 
        }
        return act;
    }
     
}

Thanks.
shikher jainshikher jain
I wrote the following code :
public class AccountHandler {
    public static Account insertNewAccount(String name) {
        Account a = new Account();
        a.Name = name;
        try
            {
            insert a;
            } 
        catch (Exception e) {
            return null;
            }
        return a;
   }
}    

But i got error : "
There was an unexpected error in your org which is preventing this assessment check from completing: System.NullPointerException: Attempt to de-reference a null object".

Could you please check it and give me the solution of this problem.

Thanks in Advance
Rich FiekowskyRich Fiekowsky
@YazzK imo, unquestionalby your best crash-course in Apex is to use Trailhead. If you don't need the techniques in a unit, you can go back to the module and skip to another unit. The same goes for trails and trailmixes. 
The problem with many excellent books and websites is that you don't know how many years since they were updated. Things change fast.      
Rich FiekowskyRich Fiekowsky
@shikher jain   Your null pointer is usually a relation field that has the value null.
No problem, unless: the field is required ; or, a validation rule requires it or uses it; or, an Apex trigger or workflow rule or process or flow or etc tries to de-reference it.
A debug log can pinpoint the culprit - read the end first. 
Shruti SandeepShruti Sandeep
@shikher jain
Change your org  from  "My Trailhead Playground 1" to different one  in the Choose your hands-on drop down.This is left to the launch button and retry the same.I hope it works!
Sandeep VelagamSandeep Velagam
Try this one, it worked. 

public class AccountHandler {
    public static Account insertNewAccount (String name){
        try{
     Account acct =  new Account();
        acct.Name = name;
        insert acct;
        return acct;
    }
    catch (DmlException e){
        return null;
    }
  }
}
Sayed Sajid AliSayed Sajid Ali
Try this it works for sure:

public class AccountHandler {
    public static Account insertNewAccount(String accName){
        try{
            Account acc = new Account(Name=accName);
            insert acc;
            return acc;
        }
        catch(DmlException e){

            return null;
        }
    }
}
Jawad AfzalJawad Afzal

Hi.
Below code is working well for this challenge.

public class AccountHandler {
    public static Account insertNewAccount(String name) {
        Account Acct = new Account();
        Acct.Name = name;
        try
        {
            insert Acct;
        } catch (Exception e) {
            return null;
        }
        return Acct;
    }
}public class AccountHandler {
    public static Account insertNewAccount(String name) {
        Account Acct = new Account();
        Acct.Name = name;
        try
        {
            insert Acct;
        } catch (Exception e) {
            return null;
        }
        return Acct;
    }
}

thankx.
Bruno Pereira 12Bruno Pereira 12

Hi all! =) 
That was the solution I developed.
I used most of the codes provided on the unit.
----------------------------------------------------------------------------------------------
 

public class AccountHandler {
 public static Account insertNewAccount(String name) {
        Account acct = new Account();
        acct.Name = name; 
     	List<Account> la = new List<Account>();
     	la.add(acct);
     
     if(String.isEmpty(name)){
     	return null;
     }else{
         try{
          Database.SaveResult[] results = Database.insert(la,false);
             for(Database.SaveResult dsr : results){
                 if(dsr.isSuccess()){
                 	system.debug('O registro ' + dsr.getId() + ' foi salvo com sucesso!');
                 }else{
                     for(Database.Error err : dsr.getErrors()){
                         system.debug('O registro recebeu um erro na hora de salvar:' + err.getStatusCode() + ' - '+ err.getMessage() );
                     }
                 }
             }
         }catch (Exception e) {
            return null;
        }
        return acct;
     }
    }
}
Amol KastureAmol Kasture
Hello all my developer friends....
In this challenge if number of you have faced the following error like 
"There was an unexpected error in your org which is preventing this assessment check from completing: System.NullPointerException: Attempt to de-reference a null object" on trailhead challenge page...

then use my code....It will work perfectly....

_________________________________________________________________________________

//The Apex class must be called AccountHandler and be in the public scope
public class AccountHandler {

   // The Apex class must have a public static method called insertNewAccount
    public static Account insertNewAccount(String actName){
       
        //The method must accept an incoming string as a parameter, which will be used to create the Account name
        Account act = new Account();
        act.Name=actName;
        
        //this is important statement...if you add then code will work & challenge will complete sure
        act.First_Name__c=actName;
        act.Last_Name__c=actName;
        try{
            //Insert the account into the system and then return the record
            insert act;
            return act;
        }
        catch(DMLException e)
        {
            //The method must also accept an empty string, catch the failed DML and then return null
            return null;
        }
    }
}

_____________________________________________________________________________________________________

Error Solution description:-  as in this Account Object few fields are required so you can assign some value or input values to it. And that fields are
First_Name__c   &
Last_Name__c

so just add this line in your code:

act.First_Name__c=actName;
act.Last_Name__c=actName;


=======================================================================================================
It will work sure....

Thank You & enjoy your challenge
 
Sandip ChahandeSandip Chahande
Hey Amol...Thanks for your help. It actually worked. :)
Leanne Ardley 7Leanne Ardley 7
I was getting the NullPointerException too, tried multiple things like turning off validation rules, changing catch to catch Exception instead of DMLException etc. The problem was actually that I had two other Account Triggers from previous exercises (in Trailhead) which were firing. I went into those triggers and commented out the lines that were calling the AccountHandlers. That solved the issue for me. 
Zhang JinruiZhang Jinrui
Why is this error reported?
There was an unexpected error in your org which is preventing this assessment check from completing: System.NullPointerException: Attempt to de-reference a null object
Vanitha AmirthalingamVanitha Amirthalingam
 I am also getting " There was an unexpected error in your org which is preventing this assessment check from completing: System.NullPointerException: Attempt to de-reference a null object" . Can anyone please help with this issue.