Exception Handling in Salesforce

Exception Handling in Salesforce

Exception:

"An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions."

Don’t forget to check out: Sharing Rules In Salesforce Security

Reasons that cause an exception:

  1. The developer is trying to dereference a null object.
  2. The developer is performing some DML and it fails.
  3. The developer is assigning a list of records to a singleton object.
  4. The developer is accessing an out of bound list index.
  5. The developer is performing some callout and it fails.
  6. The developer is mapping string value to an integer variable it will cause type exception.

There are 20 types of exceptions in Apex but the Exception class is parent class for all these 20 exceptions. Any unhandled exception terminates the process immediately and all the DML that has performed before the exception occurs rolled back completely.

How to handle an exception in Salesforce Apex?

Apex uses the try, catch, and finally block to handle an exception. You “try” to run your code and if an exception occurs you catch it and write the code to handle it in the “catch” block. You write the code that must execute whether an exception occurs or not in the final block. Multiple catch blocks can be used to catch 20 different types of exceptions. You must specify the most specific exception catch block first and the most generic exception catch block at last.

Your try-catch block looks like below snippet of code:

try{
    //code that may cause an exception
}
catch (Specific Exception type ex) {
    // optional catch block to handle a specific exception
}
catch (Exception ex) {
    //Generic exception handling code here
}
finally {
    //optional finally block
    //code to run whether there is an exception or not
}

Your try-catch block for apex callout look like below snippet of code:

try{
    HttpResponse res = http.send(req);
}
catch (System.CalloutException ex){ 
    System.debug('ERROR:' + ex.getmessages());
}

Handling different types of exception:

When the catch block is used to handle exception the default way to show the exception message doesn’t exist, the developer has to build their own way. Below are some ways to handle the different caught exceptions.

  1. DML Exception:

    Dml exception occurs when you are inserting records without providing value for required fields. Dml exception can be handled by adding a message to a record using anderror() method.

    try{
        update contract;
    } 
    catch (DMLException ex){
        contract.addError('The problem in updating the contact: ‘+ex.getmessages());
    }
    finally {
        showButton = true;
    }

    Below is the screenshot showing message added using addError() method :

    contract edit

     

  2. Visualforce page Exception:

    An exception can be shown on Visualforce Page by creating a message using ApexPages.message class in your page controller. To show an exception message on your Visualforce Page your page must include <apex :pageMessages /> tag. Below is the snippet of code that should be added to catch block to create error message :

    ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.error,'Error message');
    ApexPages.addMessage(myMsg);
    

    Error message on Visualforce Page looks like below screenshot:

    2-Salesforce-How-to-show-different-apex-message-at-different-places-on-clicking-a-single-button-Webner-–-Bespoke-development-in-LMS-Salesforce-Web-and-Mobile

    Additionally, the developer can also be notified of the exception by email. The code to send an email can be added to the catch block. Here how’s your catch block look like:

    try{
        update account;
    } 
    catch (DMLException e){
        ApexPages.addMessages(e);
        // Code for sending Email
    }

    Below is the code to send an email:

    Messaging.SingleEmailMessage mail=new Messaging.SingleEmailMessage();
    String[] toAddresses = new String[] {'[email protected]'};
    mail.setToAddresses(toAddresses);
    mail.setReplyTo('[email protected]');
    mail.setSenderDisplayName('Apex error message');
    mail.setSubject('Error from Org : ' + UserInfo.getOrganizationName());
    mail.setPlainTextBody(e.getMessage());
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

Popular Salesforce Blogs