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
Tizian KirchmannTizian Kirchmann 

trailhead challenge 'manipulate records with dml'

Hi guys,

Im trying to get into apex programming by doing the trailhead challenges.
Sadly, I'm stuck at the challenge 'manipulate records with dml'. 
To my programming knowledge: I only know very few java basics from school, so I'm definetly new to it.

Here is how my code looks at the moment:
 
public class AccountHandler {
   
    public static String insertNewAccount(String name) {
        		
        Account acct = new Account();
        acct.Name = name;
        return Name;
	}
}

I would like to know if my code above is correct and how to implement the empty DML string that should return NULL.

Any help is appreciated.
Best Answer chosen by Tizian Kirchmann
Khan AnasKhan Anas (Salesforce Developers) 
Hi,

Greetings to you!

You need to use try-catch. You can use below code:
 
public with sharing class AccountHandler {
	
	public static Account insertNewAccount(String accName) {
	
		try{
			Account a = new Account(Name=accName);
			
				INSERT a;
				return a;
			
			} catch (exception e) {
				return null;
			}
			
	}

}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future.

Thanks and Regards,
Khan Anas

All Answers

Khan AnasKhan Anas (Salesforce Developers) 
Hi,

Greetings to you!

You need to use try-catch. You can use below code:
 
public with sharing class AccountHandler {
	
	public static Account insertNewAccount(String accName) {
	
		try{
			Account a = new Account(Name=accName);
			
				INSERT a;
				return a;
			
			} catch (exception e) {
				return null;
			}
			
	}

}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future.

Thanks and Regards,
Khan Anas
This was selected as the best answer
Tizian KirchmannTizian Kirchmann
Hi Khan,

thank you very much for your answer. It worked perfectly.