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
Bob Gillis 7Bob Gillis 7 

Apex Class Developer Console Error

Bob Gillis 7
I am getting "Only top-level class methods can be declared static".  I am missing something simple?

public class AccountHandler {
    public static Account insertNewAccount(String parameter) {
        try {
            Account acct = new Account(Name=parameter);
            insert acct;
            return acct;
            
        } catch (DmlException e) {
            System.debug('A DML exception has occurred:' + e.getMessage());
            return(NULL);
        }
    return acct;
    }
}
 
 
SKolakanSKolakan
Do you have AccountHandler class inside another class? If that is the case then you can not have static method inside AccountHandler class
Naresh YadavNaresh Yadav
Hi Bob Gillis 7

Use this code.
 
public static Account insertNewAccount(String parameter) {
        try {
            Account acct = new Account(Name=parameter);
            insert acct;
            return acct;
            
        } catch (DmlException e) {
            System.debug('A DML exception has occurred:' + e.getMessage());
            return(NULL);
        }
        return null;
}
And call it in developer console like "insertNewAccount('Test')"  by selecting the method and the calling statement.

According to me developer console create a super class and this class contains all code which we want to execute.
In you case there are two classes. That's why this error comes.
 
public class superClass{  <--- //  This class is hidden from user or maybe virtual
    public class AccountHandler {
        public static Account insertNewAccount(String parameter) {
            try {
                Account acct = new Account(Name=parameter);
                insert acct;
                return acct;
            
            } catch (DmlException e) {
                System.debug('A DML exception has occurred:' + e.getMessage());
                return(NULL);
           }
          return acct;
      }
   }
}

Hope this will help.
Peace.