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
denis panoudenis panou 

Small help in etuding (Manipulating Records with DML)

Hi all.Sorry for questions but i really dont understand what i do wrong
i try finish Apex Basic module
and stop in third episode

thats text of challenge

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 '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.

that's my code

public class AccountHandler {
    
     public static String insertNewAccount(String str) {
         try {

        Account acct = new Account(Name=str);
        insert acct;
             } catch (DmlException e) {
    System.debug('A DML exception has occurred: ' + e.getMessage()); 
    return null;
     }
      return str;             
    }
}

in my logic it must works, but it failed and i don't know why, please help me, what's wrong in my code?
SRKSRK
1)  it say   If the account is successfully inserted, the method should return the account record
but you are returning str that is just a account name

2) it say  The 'insertNewAccount' method must also accept an empty string, so i belive you need to put a check on the top that if str is blank or null it return null on the 1st place

 you can try this


public class AccountHandler {
    
     public static Account insertNewAccount(String str) {
 if(str 1= null)
{        
 try {
        
        Account acct = new Account(Name=str);
        insert acct;
       return acct;        
             } catch (DmlException e) {
    System.debug('A DML exception has occurred: ' + e.getMessage()); 
    return null;
     }
}
 return null;
    }
}
Ramya VelusamyRamya Velusamy
Hope this will help u


public class AccountHandler {
    public static Account insertNewAccount (String accName){        
        
    if(accName!=''){    
        try{
            Account a = new Account(Name=accName);
            insert a;
            System.debug('Account created');
            return a;
        } catch(Exception e){
            System.Debug('Account not created');
            return null;
        }
    } else {
        return null;
    }     
        
    }    
}
SRKSRK
ncie :)
denis panoudenis panou
great thanks :) all works..
SRKSRK
Can you please mark it as bast asnwer :)