Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Sunshine And March Vibes (2025 Wallpapers Edition)

      June 1, 2025

      The Case For Minimal WordPress Setups: A Contrarian View On Theme Frameworks

      June 1, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      June 1, 2025

      How To Prevent WordPress SQL Injection Attacks

      June 1, 2025

      My top 5 must-play PC games for the second half of 2025 — Will they live up to the hype?

      June 1, 2025

      A week of hell with my Windows 11 PC really makes me appreciate the simplicity of Google’s Chromebook laptops

      June 1, 2025

      Elden Ring Nightreign Night Aspect: How to beat Heolstor the Nightlord, the final boss

      June 1, 2025

      New Xbox games launching this week, from June 2 through June 8 — Zenless Zone Zero finally comes to Xbox

      June 1, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      Student Record Android App using SQLite

      June 1, 2025
      Recent

      Student Record Android App using SQLite

      June 1, 2025

      When Array uses less memory than Uint8Array (in V8)

      June 1, 2025

      Laravel 12 Starter Kits: Definite Guide Which to Choose

      June 1, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      My top 5 must-play PC games for the second half of 2025 — Will they live up to the hype?

      June 1, 2025
      Recent

      My top 5 must-play PC games for the second half of 2025 — Will they live up to the hype?

      June 1, 2025

      A week of hell with my Windows 11 PC really makes me appreciate the simplicity of Google’s Chromebook laptops

      June 1, 2025

      Elden Ring Nightreign Night Aspect: How to beat Heolstor the Nightlord, the final boss

      June 1, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Effective ways of Exception Handling in Salesforce Apex

    Effective ways of Exception Handling in Salesforce Apex

    December 31, 2024

    In Salesforce Apex, exceptions arise from various factors such as invalid operations, surpassing governor limits, or encountering critical system errors. Apex provides a comprehensive framework to handle these exceptions, enabling applications to maintain stability and avoid unexpected failures.

    How to Overcome Exceptions Effectively?

    To overcome exceptions in Salesforce Apex, follow these strategies:

    Use Try-Catch Blocks: Encapsulate risky code inside a try block and handle errors in the corresponding catch block.
    Custom Exception Classes: Create meaningful custom exceptions to handle specific business logic scenarios.
    Handle Governor Limits: Monitor and optimize resource usage to avoid governor limit exceptions.
    Utilize Finally Block: Include a finally block to clean up resources, ensuring proper execution regardless of success or failure.
    Log Errors: Use System.debug or custom logging frameworks to track and analyze exceptions.
    Graceful User Feedback: Show user-friendly error messages instead of technical jargon.
    Leverage Apex Continuations: For callouts, use asynchronous processes to manage limits efficiently.

    Different types of Exception handling in Apex:

    DML Exception:

    When we are performing the DML such as insert, update, delete and we are not populating require fields during the insertion then error occurs.

    public class ExceptionExample{
       public static void exceptionErr(){
    
           Contact conta1= new Contact();
           conta1.FirstName='John';
           insert conta1;
          }
    }

     

    In above code the dmlexception error is occurred that is shown below.

    To prevent this error, ensure that all mandatory fields are specified during the DML operation in the Apex code.

    List Exception:

    Whenever problem occurs in list in our apex code and accessing the element at an index that doesn’t exist in the list then ListException is occurred.

    Public class ExceptionExamples {
    public static void exceptErr(){
    
    List<Contact> contactList2 = [SELECT Id, Name FROM Contact WHERE Name ='SFDC Einstein'];
    system.debug('List Exception' +contactList2[0].Name);
    }
    }

    In above code ListException error is occurred that is showing below.
    Listexception

    To avoid this error we should check the size of list.

    List<Contact> contactList2 = [SELECT Id, Name FROM Contact WHERE Name ='SFMC Einstein'];
    //check the list size
    if (contactList2.size()>0){
    system.debug('List Exception' +contactList2[0].Name);
    }

    Query Exception:

    This error is occurred when there’s an issue with a SOQL. When SOQL query does not return any record and assigning that query in SObject then this error is generally occurred.

    Public class ExceptionExamples {
    
         public static void exceptErr(){
    
            Teacher__c teacherList1 = [SELECT Id, Name FROM Teacher__c WHERE Name ='Marc'];
           system.debug('teacherList'+teacherList1);
    
         }
    }

    In above code queryException error is occurred that showing below.
    Queryexception

    To avoid queryException we should use the List We can update the line in above code as

    LIST <Teacher__c> teacherList1 = [SELECT Id, Name FROM Teacher__c  WHERE Name=’Marc’];

    SObject Exception:

    This occurs when you attempt to access a field on a queried SObject record, but that field was not included in the SELECT clause of the SOQL query.

    Public class ExceptionExamples {
       public static void exceptErr(){
          List<Teacher__c> teacherList1 = [SELECT Id FROM Teacher__c];
          if(teacherList1.size()>0){
             for(Teacher__c tch: teacherList1){
                 system.debug('teacherList1'+tch.Name);
                }
              }
         }
    }

    In the code above, an SObject Exception occurs as demonstrated below.
    Sobjectexception

    To avoid this error we need to mention the field: Name in SOQL query which we want to access in apex code.

    List<Teacher__c> teacherList = [SELECT Id, Name FROM Teacher__c];

    Limit Exception:

    Salesforce imposes governor limits to optimize resource utilization and maintain platform performance. If these limits are exceeded, a LimitException is triggered.

    1.Too Many DML Statements: 151:
    The error occurs when your Apex code exceeds the maximum number of allowed DML statements in a single transaction. Salesforce enforces governor limits to ensure fair resource usage among all the executing transactions. The limit for DML statements is 150.

    Public class ExceptionExamples {
        public static void exceptErr(){
          for(integer i= 0; i<151; i++){
              Contact conta1 = new Contact();
              conta1.LastName = 'Einstein'+ i;
             insert conta1;
          }
       }
    }

    In above code limitException error is occurred that is shown below.
    151 Dmllimit

    To prohibit the error, you can bulkify your code by performing the DML operation outside the loop.

    Public class ExceptionExamples {
        public static void exceptErr(){
        List<Contact> contactList23 = new List<Contact>();
          for(integer i= 0; i<151; i++){
            Contact conta1 = new Contact();
            conta1.LastName = 'SFDC'+ i;
            contactList23.add(conta1);
           }
          if(contactList23.size()>0){
             insert contactList23;
           }
        }
    }
    //In above code error will not occur


    2.Too Many SOQL Queries: 101:

    This error occurs in Salesforce when your Apex code or triggers exceed the permissible number of SOQL queries within a single transaction. The governor limit for SOQL queries in a transaction is 100.

    Public class ExceptionExamples {
      public static void exceptErr(){
       List<Contact> contactList2 = new List<Contact>();
       for(integer i= 0; i<101; i++){
        List<Contact> con = [SELECT Id, Name, Phone FROM Contact WHERE Name Like '%contact%'];
        system.debug('Exception'+con[0].Name);
       }
      }
    }

    In above code limitException error is occurred that is showing below.
    Soqllimit

    To avoid this error we need to move the soql query outside the for loop to avoid the too many soql query in apex code.

    Public class ExceptionExamples {
      public static void exceptErr(){
       List<Contact> con = [SELECT Id, Name,Phone FROM Contact WHERE Name Like '%contact%'];
       for (integer i = 0; i < 101; i++){
          // You can use the con variable to access the query results
            system.debug('Exception ' + con[0].Name);
        }
      }
    }//In above code error will not occur.

    NullPointer Exception:

    A NullPointerException in Apex occurs when we trying to access a null object reference. This error indicates that our code is trying to perform an operation on an object that is not instantiated.

    Public class ExceptionExamples {
      public static void exceptErr(){
        Account acc;
       System.debug('NullPointerException'+acc.Name);
       }
    }

    In above code NullPointerException error is occurred that is showing below.
    NullPointerException
    To avoid this error, we need to assign the value before accessing in our code

    if (acc != null) {
    System.debug(acc.Name);
    } else {
    System.debug('Account is null');
    }

    Reference:Exceptions in Apex

    Conclusion

    Exception handling is a critical aspect of Salesforce Apex development that ensures your applications are robust, reliable, and user-friendly. By proactively identifying potential failure points, implementing structured try-catch-finally blocks, and creating meaningful custom exceptions, you can build resilient solutions that gracefully handle unexpected scenarios. Always remember to log errors for debugging, optimize your code to respect governor limits, and provide clear feedback to users. With these practices, you can turn challenges into opportunities to enhance your code’s quality and maintainability. Happy coding!

    Read more about different Salesforce topics:

    1. FlexCards in Salesforce OmniStudio: A Beginner’s Guide
    2. Mastering Salesforce OmniScript: A Comprehensive Guide to Streamlined Workflows
    3. Seamless Data Integration with Salesforce OmniStudio DataRaptor
    4. Unlocking the Power of Salesforce OmniStudio Integration Procedure: An In-Depth Guide

    Source: Read More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleOptimizing Core Web Vitals for Modern React Applications
    Next Article JavaScript Memory Leaks: How to Identify and Fix Them

    Related Posts

    Security

    New Linux Flaws Allow Password Hash Theft via Core Dumps in Ubuntu, RHEL, Fedora

    June 2, 2025
    Security

    Google AI Edge Gallery: Unleash On-Device AI Power on Your Android (and Soon iOS!)

    June 2, 2025
    Leave A Reply Cancel Reply

    Continue Reading

    Automatically Format Code On File Save in Visual Studio Code

    Linux

    Kubernetes turns 10: How it steered cloud-native computing for the last decade – and what’s next

    Development

    Mastering SFMC Automation Studio: Activities, Capabilities, and Journey Integration

    Development

    CVE-2025-26892 – dkszone Celestial Aura Unrestricted File Upload RCE

    Common Vulnerabilities and Exposures (CVEs)

    Highlights

    News & Updates

    How to share files with sensitive content securely on Windows 11

    April 17, 2025

    On Windows 11, if you have to share a file with confidential information, you can…

    How Legend Srinidhi Ranganathan’s Idea can Propel India to Become the World’s Richest Country?

    August 19, 2024

    Top Artificial Intelligence AI Courses from Salesforce

    June 9, 2024

    Learning Intuitive Physics: Advancing AI Through Predictive Representation Models

    February 19, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.