Search code examples
apex-code

Exception handling with Apex (force.com)


Is there any way to throws an standard or custom exception with Apex method as,

 private void createNewJob() throws RecordNotFoundException { 

  try {         
         // Some DML operation                
      } catch (Exception e) {  
         System.Debug('Error: Object not found');
         throw new RecordNotFoundException('Object not found');
      }
  }

Solution

  • Yes.

    Define the exception class. Minimally, :

    public class RecordNotFoundException extends Exception { }
    

    Your throw statement looks fine.

    Also, there's no need to declare that the method throws an exception type.