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

      Sunshine And March Vibes (2025 Wallpapers Edition)

      May 31, 2025

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

      May 31, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      May 31, 2025

      How To Prevent WordPress SQL Injection Attacks

      May 31, 2025

      How to install SteamOS on ROG Ally and Legion Go Windows gaming handhelds

      May 31, 2025

      Xbox Game Pass just had its strongest content quarter ever, but can we expect this level of quality forever?

      May 31, 2025

      Gaming on a dual-screen laptop? I tried it with Lenovo’s new Yoga Book 9i for 2025 — Here’s what happened

      May 31, 2025

      We got Markdown in Notepad before GTA VI

      May 31, 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

      Oracle Fusion new Product Management Landing Page and AI (25B)

      May 31, 2025
      Recent

      Oracle Fusion new Product Management Landing Page and AI (25B)

      May 31, 2025

      Filament Is Now Running Natively on Mobile

      May 31, 2025

      How Remix is shaking things up

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

      How to install SteamOS on ROG Ally and Legion Go Windows gaming handhelds

      May 31, 2025
      Recent

      How to install SteamOS on ROG Ally and Legion Go Windows gaming handhelds

      May 31, 2025

      Xbox Game Pass just had its strongest content quarter ever, but can we expect this level of quality forever?

      May 31, 2025

      Gaming on a dual-screen laptop? I tried it with Lenovo’s new Yoga Book 9i for 2025 — Here’s what happened

      May 31, 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

    Hostinger

    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 

    Hostinger
    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 Apache InLong Vulnerability (CVE-2025-27522) Exposes Systems to Remote Code Execution Risks

    May 31, 2025
    Security

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

    May 31, 2025
    Leave A Reply Cancel Reply

    Continue Reading

    Call of Duty: Warzone’s Caine Trailblazer skin is the ultimate chase right now — here’s how to give yourself the best shot at getting it fast

    Call of Duty: Warzone’s Caine Trailblazer skin is the ultimate chase right now — here’s how to give yourself the best shot at getting it fast

    News & Updates

    Beyond Swords and Spells: 7 Video Games Where You Can Become a Master Hacker

    Development

    Surface Copilot+ PC and new AI job roles lead the Innovation Index

    Development

    North Korean Hackers Shift from Cyber Espionage to Ransomware Attacks

    Development
    GetResponse

    Highlights

    A Guide to the Best AI-Powered Video Editing Tools

    July 5, 2024

    Post Content Source: Read More 

    REDA: A Novel AI Approach to Multi-Agent Reinforcement Learning That Makes Complex Sequence-Dependent Assignment Problems Solvable

    January 4, 2025

    DeepSeek AI Introduces CODEI/O: A Novel Approach that Transforms Code-based Reasoning Patterns into Natural Language Formats to Enhance LLMs’ Reasoning Capabilities

    February 16, 2025

    Identifying and Mitigating Risks from Drunk and Impaired Drivers on the Road

    June 12, 2024
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

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