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.” [1]

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 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 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 finally block. Multiple catch blocks can be used to catch 20 different types of exception. You must specify the most specific exception catch block first and the most generic exception catch block at last.

Your try-catch block look 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 catch block is used to handle exception the default way to show 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 message to a record using addError() 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 :

    In-474

  2. Visualforce page Exception:Exception can be show on visualforce page by creating a message using ApexPages.message class in your page controller. To show an exception message on your visualforce page you 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 look 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 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 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 });}
    

———————-

Reference:
https://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html

0 Comments

Leave a Reply

CONTACT US

We're not around right now. But you can send us an email and we'll get back to you, asap.

Sending

About Us

Forcetalks is a Salesforce collaboration platform for coders & developers, geeks & nerds, consultants & business heads, admins & architects, managers & marketers and of course the business owners. A community where you can learn from, where you can contribute to. For you. For Salesforce. Read More...

Copyright 2018 Forcetalks. All Right Reserved.

Log in with your credentials

or    

Forgot your details?