I am new to language Apex and learning basic stuff. I have follwing code (written for a trailhead challenge) and wondering about the success.

public static Account insertNewAccount(String AccountName) {
    Account acc = new Account(name = AccountName);

    try {
        insert acc;    
    catch (DmlException e) {
        acc = null;

    return acc;

The definition of the method says it will return an sObject Account - why is it possible to return a null instead? Are there better ways to declare that method will return Account OR Null?


Null can be any type. So returning a Null Account is perfectly valid.

You never need to declare that an Account will return an Account OR Null (and this is not possible) because every complex and primative data type can be Null.

See here for more information about primitive data types: Primitive Data Types and here: Data Types

More about Null here:

If you declare a variable and don't initialize it with a value, it will be null. In essence, null means the absence of a value.

You can also assign null to any variable declared with a primitive type.

Reference here: Variables

  • Yes I agree, If your function usually returns something but doesn't for some reason, return null; is the way to go. And it is always is a good practice to show what you're returning. May 16 '17 at 9:06
  • 4
    @RohitMourya I disagree when it comes to collections. Never return a null collection when you can avoid it.
    – Adrian Larson
    May 16 '17 at 11:48
  • @AdrianLarson Yes, makes sense. May 16 '17 at 12:26
  • A variable of any type can be null (not just complex ones), which leads to some weird things like booleans that are neither true nor false. May 16 '17 at 12:51
  • 1
    I'm with you @AdrianLarson - never return a null collection - fixed the omission in the answer too (I was unsure about integers for some reason and had a quick check, but then forgot to update the answer) May 16 '17 at 16:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.