Types of Exceptions in Apex Programming

Types of Exceptions in Apex Programming: 

When developing in Salesforce’s Apex programming language, understanding exceptions—and how to handle them—is crucial for building resilient applications. Apex supports two types of exceptions: 

  • System-Defined (Built-in) Exceptions 
  • User-Defined (Custom) Exceptions 

Let’s dive deeper into each of these categories. 

  1. System-Defined Exceptions:

Apex provides many built-in exception classes that the runtime engine automatically throws when an error occurs. Some common system exceptions include: 

  • ListException 
  • LimitException 
  • DMLException 
  • ArrayIndexOutOfBoundsException 
  • MathException (e.g., DividedByZeroException) 
  • QueryException 
  • CalloutException 
  • FileNotFoundException 
  • NullPointerException 
  • …and more. 

Common Examples: 

  • DML Exception (e.g., inserting a record without required fields) 

Account acc = new Account(); 

insert acc; 

  • Query Exception (e.g., querying a single record that returns multiple rows) 

Account acc = [SELECT Id, Name, Rating FROM Account]; 

  • NullPointer Exception 

String s; 

System.debug(‘Search for characters: ‘ + s.contains(‘ab’)); 

  • Math Exception 

System.debug(‘Division Result: ‘ + (234/0)); 

  • List Exception (e.g., accessing an out-of-bounds list index)

List<String> lstCountries = new List<String>{‘India’, ‘USA’}; 

System.debug(lstCountries[2]); // Index out of bounds 

Handling Exceptions in Apex: 

To gracefully handle runtime errors, Apex provides the Try-Catch-Finally construct. 

Try Block: 

The try block encloses code that might throw an exception, such as DML operations or SOQL queries. 

Catch Block: 

The catch block catches and handles specific exceptions thrown in the try block. You can have multiple catch blocks for different exception types. 

Finally Block: 

The finally block contains code that will execute regardless of whether an exception occurs—typically used for resource cleanup. 

Syntax: 

try { 

    // Code that might throw an exception 

} catch (ExceptionType e) { 

    // Code to handle the exception 

} finally { 

    // Cleanup code 

} 

 

Note: All system-defined exceptions ultimately extend the base Exception class. 

Example: Handling Multiple Exceptions 

public class ExceptionTestClass { 

    public void doMoreStuff() { 

        Account acc; 

        try { 

            acc = new Account(); 

            acc.Name = ‘Sample’; 

            insert acc; 

 

            System.debug(‘Division Result: ‘ + (890/0)); // Math exception 

        } 

        catch (DMLException ex) { 

            System.debug(‘DML Exception occurred.’); 

        } 

        catch (QueryException ex) { 

            System.debug(‘Query Exception occurred.’); 

        } 

        catch (NullPointerException ex) { 

            System.debug(‘NullPointerException occurred.’); 

        } 

        catch (MathException ex) { 

            System.debug(‘Math operation caused an exception.’); 

        } 

        finally { 

            acc = null; 

        } 

    } 

} 

Execution:  

ExceptionTestClass ex = new ExceptionTestClass(); 

ex.doMoreStuff(); 

Exception Class Methods in Apex: 

The Exception class provides useful methods for understanding and debugging exceptions: 

Method  Description 
getMessage()  Returns the exception message. 
getStackTraceString()  Returns a string of the stack trace. 
getLineNumber()  Returns the line number where the exception occurred. 
getCause()  Returns the cause of the exception. 
getTypeName()  Returns the type of the exception. 

Example: Using Exception Methods 

public class ExceptionHandlerClass { 

    public static void handleExceptions() { 

        Account acc = new Account(); 

        try { 

            acc = [SELECT Id, Name, Rating, AnnualRevenue FROM Account]; 

            System.debug(‘Account Records: ‘ + acc); 

        } 

        catch (QueryException qEx) { 

            System.debug(‘Query Exception occurred’); 

            System.debug(‘Type: ‘ + qEx.getTypeName()); 

            System.debug(‘Message: ‘ + qEx.getMessage()); 

            System.debug(‘Line Number: ‘ + qEx.getLineNumber()); 

            System.debug(‘Stack Trace: ‘ + qEx.getStackTraceString()); 

            System.debug(‘Cause: ‘ + qEx.getCause()); 

        } 

        catch (Exception ex) { 

            System.debug(‘General Exception Error Occurred.’); 

        } 

        finally { 

            acc = null; 

        } 

    } 

} 

Execution: 

ExceptionHandlerClass.handleExceptions(); 

  1. User-Defined Exceptions:

Built-in exceptions often display technical error messages that may not be user-friendly. To provide meaningful error messages, developers can define custom exceptions. 

Creating a Custom Exception: 

 

To define a custom exception, extend the built-in Exception class. The class name should end with Exception, otherwise, Apex will throw a compilation error. 

public class AccountException extends Exception { 

} 

Example: Using a Custom Exception 

public class ExceptionHandlerClass { 

    public static void insertAccount() { 

        Account acc; 

        try { 

            acc = new Account(); 

            insert acc; 

        } 

        catch (DMLException ex) { 

            throw new AccountException(‘Exception occurred while inserting Account record’); 

        } 

        finally { 

            acc = null; 

        } 

    } 

} 

Execution: 

ExceptionHandlerClass.insertAccount(); 

 

Leave a Comment

Your email address will not be published. Required fields are marked *