Exception Handling in Apex

Exception Handling is a mechanism in salesforce to handle unwanted exceptions or errors in our code without the exception breaking the flow of the code.

This is a practice which allows the developers to handle any exceptions in their code, which allows them to account for any errors in the system. This is a best practice that should be followed while developing apex classes.

Exception handling is done in apex by using the try and catch mechanism, basically any code which can throw an exception is enclosed in a try block and each try block is followed by a catch block which is entered if the try block throws an exception.

try{
	// Exception prone Code
}
catch(Exception e){
	// Handle the exception
}

Exceptional Handling – try, catch, finally, throw keywords

Exception occurs during the run time / execution of a program. We have to handle the excretion in code. Like java, apex has exception handling mechanism. Below are the Keywords(try, catch, finally, throw ) related to an Exceptional Handling.

try: This keyword is used to identifies a block of code in which an exception can occur.

Example:

try {
    // Your code here
} catch (ListException e) {
    // List Exception handling code here
}

catch: This keyword is used to identifies a block of code that can handle a particular type of exception.

Example:

try {
    // Your code here
} catch (ListException e) {
    // List Exception handling code here
}

finally: This keyword is used to identifies a block of code that is guaranteed to execute.

Example:

try {
    // Your code here
} catch (ListException e) {
    // List Exception handling code
} finally {
    // will execute with or without exception
}

throw: This keyword is used to throws an exception, signaling that an error has occurred.

Example:

public class MyException extends Exception {
    try {
        Integer i;
        if (i < 5)
        throw new MyException();
    } catch (MyException e) {
        // Your MyException handling
        // code here
    }
}

Commonly used exceptions in Apex

1. DmlException
Any problem with DML statement, such as an insert statement missing a required field a record.
Example

try {
  Merchandise__c m = new Merchandise__c();
  insert m;
} catch(DmlException e) {
  System.debug(‘The following exception has occurred: ‘ + e.getMessage());
}

2. Limit exception

Governor limits are runtime limits which are enforced by the Apex runtime engine. Because Apex runs in a shared and multi-tenant environment, the Apex runtime engine strictly enforces a number of limits to ensure that code does not take over shared resources. Types of limits that Apex enforces are resources like database, memory, number of script statements to avoid infinite loops, and the number of records being processed in a transaction. If the code exceeds a defined limit, the associated governor fires a runtime exception.

Example

Create an object with label Test Object with only one field Name which is of text type. Write an class that is used to inserts 300 records in Test Object.

public class TestDataController {
  public static Test_Object__c test;
  public static void massInsert(){
  for(Integer count = 0; count < 300; count++){
    test = new Test_Object__c();
    test.Name = ‘data field ‘ + count;
    insert test;
  }
}

now it's time to call the static method from your developer Console as shown below

From that Open Developer Console

TestDataController.massInsert();

Debug -> Open Execute Anonymous Window OR (CTRL + E).

Call TestDataController.massInsert(); as shown above.

Click Execute.

You can see that no rows are updated. The exception is
System.LimitException.

3. List Exception

Any problem with a list, for example attempting to access an index that is out of bound.

Example

try{
  List li = new List();
  li.add(10);
  Integer i1 = li[0];
  Integer i1 = li[1]; // List exception
 
}catch(listException le){
  System.debug(‘The Exception is : ‘+le.getMessage());
 
}

4. Math Exception

Any problem with mathematical operation, such as divide by zero.

Example

Integer i= 1/0; // System.MathException

5. NullPointer Exception

This type of exception occur when you are trying to call a method with null i.e. if a variable is pointing to null and you are trying to call a method cause a NullPointerException.The exception is caught in our defined catch block and this is what is written to the debug log: The below exception has occurred: Attempt to de-reference a null object.

Example

String s;
s.toLowerCase(); // Since s is pointing to null, this call causes 
// a NullPointerException
or
try {
  String s;
  Boolean b = s.contains(‘abc’); // Causes a NullPointerException
} catch(NullPointerException npe) {
  System.debug(‘The following exception has occurred: ‘ + npe.getMessage());
}

6. QueryException:

Any problem with SOQL queries, like assigning a query that returns no records or you can say more than one record to a singleton sObject variable.

Example

try {
  // This statement doesn’t cause an exception, even though
  // we don’t have a merchandise with name=’XYZ’.
  // The list will just be empty.
  List lm = [SELECT Name FROM Merchandise__c WHERE Name=’XYZ’];
  // lm.size() is 0
  System.debug(lm.size());
  // However, this statement causes a QueryException because
  // we’re assigning the return value to a Merchandise__c object
  // but no Merchandise is returned.
  Merchandise__c m = [SELECT Name FROM Merchandise__c WHERE Name=’XYZ’ LIMIT 1];
} catch(QueryException qe) {
  System.debug(‘The following exception has occurred: ‘ + qe.getMessage());
}

7. Creating Custom Exceptions

Since you cannot throw salesforce built-in Apex exceptions but can only catch them, you can create custom exceptions to throw in your methods as per your requirement. That way, you can also specify detailed error messages and have much more custom exception handling in your defined catch blocks. To create your custom exception class, extends with the keyword Exception(Which is the super class of all the exception class either built-in or custom). Append extends Exception after your class declaration as given below:

Syntax

public class MyException extends Exception {}

Example

Public class ContactException extends Exception{}
public class ContactUtility {
  public static void mainProcessing() {
    try {
    insertContact();
    }catch(ContactException me) {
      System.debug(‘Message: ‘ + me.getMessage());
      System.debug(‘Cause: ‘ + me.getCause());
      System.debug(‘Line number: ‘ + me.getLineNumber());
      System.debug(‘Stack trace: ‘ + me.getStackTraceString());
    }
  }
  public static void insertContact() {
    try {
      // Insert Contact without required fields
      Contact m = new Contact();
      insert m;
    } catch(DmlException e) {
      // Something happened that prevents the insertion
      // of Contact objects, so throw a more
      // specific exception.
      throw new ContactException(‘Contact could not be inserted.’, e);
    }
  }
}
Subscribe Now