Salesforce Exceptions Explained: Types, Examples and How to Fix Them (2026)

TL;DR: An exception in Salesforce is a runtime error that stops your Apex code unless you catch it. This guide explains the most common built-in exceptions, what causes each one, and how to fix it. You will also learn how to write custom exceptions, why a LimitException cannot be caught, and how to log errors in production. Use the quick-reference table to find your error fast.

Last updated: October 2026.

Salesforce exceptions are the errors that show up when Apex code breaks at runtime. You have probably seen messages like Attempt to de-reference a null object or List has no rows for assignment to SObject. Each one is a different type of exception, and each has a clear cause and a clear fix.

Most guides list a handful of exception types and stop there. This one goes further. You will see the cause, a code example and a fix for each common exception. You will also learn which errors you cannot catch, how to build your own, and how to track errors after you deploy.

If you are new to writing safe Apex, read our Apex best practices guide alongside this one.

What Is an Exception in Salesforce?

An exception in Salesforce is a runtime error that interrupts the normal flow of Apex code. If nothing catches it, the whole transaction stops and rolls back, and the user sees an error. You can catch an exception with a try-catch block and handle it safely.

Every exception extends the base Exception class. Salesforce gives you built-in types like DmlException and QueryException, and you can write your own. The Apex reference for built-in exceptions lists about 40 of them.

Methods every exception gives you

  • getMessage(): the error text a user can read.
  • getTypeName(): the exception type, such as DmlException.
  • getLineNumber(): the line where it was thrown.
  • getStackTraceString(): the chain of calls that led to the error.
  • getCause(): the original exception, when one error wraps another.

How try, catch and finally work

Put risky code in a try block. If it throws, Apex jumps to the first catch block that matches the exception type. A finally block runs every time, whether or not an error happened.

try blockYour code runsException thrown?No: skip the catchYes: matching catch runsfinally blockAlways runsCode continuesIf it was caught
try {
    Account acc = [SELECT Id, Name FROM Account WHERE Name = 'Acme' LIMIT 1];
    acc.Industry = 'Energy';
    update acc;
} catch (QueryException e) {
    System.debug('No account found: ' + e.getMessage());
} catch (DmlException e) {
    System.debug('Save failed: ' + e.getDmlMessage(0));
} catch (Exception e) {
    System.debug(e.getTypeName() + ' at line ' + e.getLineNumber());
} finally {
    System.debug('This line always runs');
}

Keep these rules in mind:

  • Put specific catch blocks first and the generic Exception last. Apex will not compile if a general catch comes before a specific one.
  • Once you catch an exception, the transaction keeps going. Any DML that ran before the error is still saved unless you roll back to a savepoint.
  • Use finally for clean-up that must always happen, such as resetting a static flag.

What Are the Most Common Built-In Exceptions in Salesforce?

The most common built-in exceptions in Salesforce are DmlException, QueryException, NullPointerException, ListException, TypeException, MathException, JSONException and CalloutException. Each one points to a specific mistake, such as a failed save, an empty query or an unchecked null value. Here is what causes each one and how to fix it.

1. DmlException

Cause: An insert, update, delete or upsert failed. Common reasons are a missing required field, a validation rule, a duplicate rule or a record that is locked.

Fix: Read the details for each failed row. A single DML statement can fail on many records, so loop through the errors instead of reading only the first message. To save the good records and report the bad ones, use Database.insert(records, false).

try {
    insert new Contact(FirstName = 'Asha'); // LastName is required
} catch (DmlException e) {
    for (Integer i = 0; i < e.getNumDml(); i++) {
        System.debug(e.getDmlType(i) + ': ' + e.getDmlMessage(i));
        System.debug('Failed row index: ' + e.getDmlIndex(i));
    }
}

2. QueryException

Cause: A SOQL query failed. The classic cases are List has no rows for assignment to SObject and List has more than 1 row for assignment to SObject. Both happen when you assign a query result to a single record and the query returns zero or many rows.

Fix: Query into a list and check it before you use the first item. If you run a query in user mode, the exception can also tell you which fields the user cannot read through getInaccessibleFields().

// Throws QueryException when zero or many rows match
Account acc = [SELECT Id FROM Account WHERE Name = 'Missing'];

// Safe: query into a list, then check it
List<Account> accounts = [SELECT Id FROM Account WHERE Name = 'Missing' LIMIT 1];
if (!accounts.isEmpty()) {
    Account safeAcc = accounts[0];
}

3. NullPointerException

Cause: You used a variable that holds null. The message reads Attempt to de-reference a null object. It often comes from a map lookup that found nothing, a related record that was not queried, or a method call on a null string.

Fix: Check for null before you use a value. Apex also has the safe navigation operator ?. and the null coalescing operator ??, which keep these checks short.

Contact con = contacts.isEmpty() ? null : contacts[0];

// Throws NullPointerException if con or con.Account is null
String risky = con.Account.Name;

// Safe version
String accountName = con?.Account?.Name;
String label = accountName ?? 'No account';

4. ListException and NoSuchElementException

Cause: You asked for a position that does not exist. Reading accounts[0] on an empty list throws a ListException with the message List index out of bounds: 0. A NoSuchElementException is the same idea for iterators, such as calling next() after the last item.

Fix: Check isEmpty() or size() first, and use hasNext() before next().

5. TypeException, MathException and StringException

These three are simple to spot and simple to fix.

  • TypeException: a value cannot be converted, such as Integer.valueOf('abc'). Validate the text first, or catch the exception.
  • MathException: a math rule was broken, such as dividing by zero. Check that the divisor is not zero.
  • StringException: a string operation failed, such as turning an invalid text into an Id with Id.valueOf('abc'). Check the length and format of the text first.

6. SObjectException

Cause: You used a field in a way the record does not allow. The most common message is SObject row was retrieved via SOQL without querying the requested field. It means you read a field that was not in your SELECT list.

Fix: Add the field to the query. In a trigger, remember that Trigger.new in a before context holds only the fields on the record, not related data.

Account acc = [SELECT Id, Name FROM Account LIMIT 1];
System.debug(acc.Industry); // SObjectException: Industry was not queried

Account fixed = [SELECT Id, Name, Industry FROM Account LIMIT 1];
System.debug(fixed.Industry);

7. JSONException

Cause: Salesforce could not read or write JSON. This usually means the text is not valid JSON, or the JSON does not match the Apex class you are deserializing into.

Fix: Catch the exception around JSON.deserialize(), log the raw text, and fix the mismatch. Our guide to JSON in Apex shows how to build matching classes.

try {
    Map<String, Object> data = (Map<String, Object>) JSON.deserializeUntyped(responseBody);
} catch (JSONException e) {
    System.debug('Bad JSON: ' + e.getMessage());
}

8. CalloutException

Cause: A call to an outside service failed. Typical messages are Unauthorized endpoint, please check Setup, Security, Remote site settings, Read timed out, and You have uncommitted work pending. The last one means you made DML before the callout in the same transaction.

Fix: Use a Named Credential so the endpoint is allowed and the secret is stored safely. Make the callout before any DML, or move it to a Queueable job. Set a timeout and retry with care. Our integration interview questions go deeper on callout design.

try {
    HttpRequest req = new HttpRequest();
    req.setEndpoint('callout:Billing_API/invoices');
    req.setMethod('GET');
    req.setTimeout(20000);

    HttpResponse res = new Http().send(req);
    if (res.getStatusCode() != 200) {
        throw new CalloutException('Billing API returned ' + res.getStatusCode());
    }
} catch (CalloutException e) {
    System.debug('Callout failed: ' + e.getMessage());
}

9. FinalException

Cause: You tried to change something that is read-only. The classic case is Record is read-only, which appears when you edit Trigger.new records in an after trigger.

Fix: Make field changes on the same record in a before trigger. In an after trigger, query a fresh copy of the record, change it and update it. Our complete guide to Apex triggers explains before and after contexts.

10. AuraHandledException

Cause: This is not an error in itself. It is the exception you throw from an @AuraEnabled method so a Lightning component receives a clear message. The Salesforce guide to Apex error handling in Lightning recommends this approach.

Watch out: Without extra work, getMessage() on an AuraHandledException can return Script-thrown exception instead of your text. Call setMessage() as well to fix it, especially in tests.

@AuraEnabled
public static void saveOrder(Id orderId) {
    try {
        // business logic here
    } catch (DmlException e) {
        AuraHandledException ex = new AuraHandledException('We could not save the order.');
        ex.setMessage('We could not save the order.');
        throw ex;
    }
}

Can You Catch a LimitException in Apex?

No. A LimitException is thrown when your code goes over a governor limit, and Apex cannot catch it. The transaction stops at once and rolls back. The only fix is to write code that stays under the limits in the first place.

The Salesforce exception reference marks it as the one you cannot catch. You will see it in messages like these:

  • Too many SOQL queries: 101: a query inside a loop.
  • Too many DML statements: 151: DML inside a loop.
  • Apex CPU time limit exceeded: slow loops or heavy logic.
  • Apex heap size too large: too much data held in memory at once.

Since you cannot catch it, you must prevent it. Bulkify your code, keep SOQL and DML out of loops, and use SOQL for loops for large queries. The Limits class lets you check how close you are before you cross the line. See our governor limits guide for every number.

How Do You Create a Custom Exception in Apex?

To create a custom exception in Apex, write a class whose name ends in Exception and that extends the Exception class. You can then throw it with a message and catch it like any built-in exception. Custom exceptions give business rule errors a clear name.

public class InvoiceException extends Exception {}

public with sharing class InvoiceService {

    public static void create(Decimal amount) {
        if (amount == null || amount <= 0) {
            throw new InvoiceException('Invoice amount must be greater than zero.');
        }
        // create the invoice here
    }
}

// Catching it
try {
    InvoiceService.create(-5);
} catch (InvoiceException e) {
    System.debug('Business rule broken: ' + e.getMessage());
}

You can also wrap a lower-level error and keep the original as the cause. This keeps the full story in the stack trace.

try {
    insert invoiceRecords;
} catch (DmlException e) {
    throw new InvoiceException('Could not save invoices', e);
}
  • Name the exception after the business problem, such as InvoiceException.
  • Throw early, as soon as you see bad input.
  • Do not use exceptions to control normal program flow. Use an if check instead.
  • Never leave a catch block empty. Log it or rethrow it.

How Do You Handle Exceptions in Triggers, Lightning Components and Async Jobs?

Each place that runs Apex needs its own way to report errors. In a trigger, use addError(). In a Lightning component, throw an AuraHandledException. In an async job, use a Finalizer to catch failures you would otherwise miss.

Triggers: use addError()

The addError() method marks a record as failed and shows your message to the user. It is the right choice for business rule checks, because it does not need an exception at all.

trigger OpportunityTrigger on Opportunity (before update) {
    for (Opportunity opp : Trigger.new) {
        if (opp.StageName == 'Closed Won' && opp.Amount == null) {
            opp.Amount.addError('Amount is required before you close this deal.');
        }
    }
}

Async jobs: use a Finalizer

When a Queueable job fails, the user never sees the error. It only appears in the Apex Jobs page. A Finalizer is a class that runs after the job ends, so you can log the failure and decide what to do next.

public class SyncAccountsJob implements Queueable {
    public void execute(QueueableContext context) {
        System.attachFinalizer(new SyncFinalizer());
        // slow work or callouts go here
    }
}

public class SyncFinalizer implements Finalizer {
    public void execute(FinalizerContext ctx) {
        if (ctx.getResult() == ParentJobResult.UNHANDLED_EXCEPTION) {
            ErrorLogger.log('SyncAccountsJob', ctx.getException());
        }
    }
}

The ErrorLogger class in this example is the platform event logger from practice 19 in our Apex best practices guide. For Batch Apex, catch errors inside execute() and use the Database methods so one bad record does not fail the whole chunk.

How Do You Test That Your Code Throws an Exception?

To test an exception in Apex, call the code inside a try-catch block, call Assert.fail() right after the risky line, and check the caught exception. If no exception is thrown, the test fails. This proves your error handling really works.

@IsTest
private class InvoiceServiceTest {

    @IsTest
    static void rejectsNegativeAmount() {
        try {
            InvoiceService.create(-5);
            Assert.fail('Expected an InvoiceException');
        } catch (InvoiceException e) {
            Assert.isTrue(e.getMessage().contains('greater than zero'));
        }
    }
}

Test the other side too. Send good input and check that no exception is thrown. For more test habits, see practice 16 in our Apex best practices guide.

How Do You Track Apex Exceptions in Production?

You can track Apex exceptions through unhandled exception emails, debug logs, the ApexExceptionEvent object, and your own logging. Salesforce only reports exceptions nobody caught, so a swallowed error leaves no trace. Plan your logging before you go live.

  • Unhandled exception emails: Salesforce emails admins with the exception type, message and stack trace. The detail is limited, and exceptions you catch send no email, as explained in Gearset’s guide to Apex error monitoring.
  • Debug logs: good for chasing one bug, but they expire and are hard to search.
  • ApexExceptionEvent: an event you can read through the Tooling API, listed by Gearset as a native monitoring option.
  • Your own error log: publish a platform event from every catch block so the record survives a rollback.
  • Apex Jobs page: shows failed Queueable, Batch and scheduled jobs.

Salesforce Exceptions Quick Reference

Search this table for the message you see. It shows the exception, what usually causes it and the quickest fix.

ExceptionTypical messageUsual fix
DmlExceptionREQUIRED_FIELD_MISSING, validation errorsLoop through failed rows and fix the data
QueryExceptionList has no rows for assignment to SObjectQuery into a list and check isEmpty()
NullPointerExceptionAttempt to de-reference a null objectAdd a null check or use ?.
ListExceptionList index out of bounds: 0Check size() before reading an index
TypeExceptionInvalid integer: abcValidate text before converting
MathExceptionDivide by 0Check the divisor first
StringExceptionInvalid idCheck the text format before building an Id
SObjectExceptionSObject row was retrieved via SOQL without querying the requested fieldAdd the field to the SELECT list
JSONExceptionUnexpected character or unable to parse JSONCheck the JSON and the target class
CalloutExceptionUnauthorized endpoint, or uncommitted work pendingUse a Named Credential and callout before DML
FinalExceptionRecord is read-onlyChange fields in a before trigger
LimitExceptionToo many SOQL queries: 101Bulkify the code. It cannot be caught.

Frequently Asked Questions

What is the difference between an error and an exception in Salesforce?

An error is any problem, including compile errors you see before the code runs. An exception is a runtime problem that Apex throws while the code is running. You can catch most exceptions with try-catch, but not a LimitException.

Can you catch a LimitException in Apex?

No. A LimitException happens when your code breaks a governor limit, and Apex cannot catch it. The transaction stops and rolls back. Prevent it by bulkifying your code and keeping SOQL and DML out of loops.

What is the difference between getMessage() and getStackTraceString()?

The getMessage() method returns the readable text of what went wrong. The getStackTraceString() method returns the chain of classes and line numbers that led to the error. Log both so you can find and fix the problem quickly.

How do you fix Attempt to de-reference a null object?

This NullPointerException means you used a variable that is null. Find the variable on the line in the stack trace, then add a null check or use the safe navigation operator ?. before you read a field or call a method.

What is a custom exception in Apex?

A custom exception is a class you write that extends the Exception class, and its name must end in Exception. You throw it to signal a business rule problem, such as a bad invoice amount, and catch it like any built-in exception.

Conclusion

Salesforce exceptions are not scary once you know what each one means. Read the type, read the message, then fix the cause. Three habits will save you the most time:

  • Catch specific exceptions and never leave a catch block empty.
  • Prevent LimitExceptions, because you cannot catch them.
  • Log errors somewhere they survive a rollback.

Want to practice these in a mock interview, or get your code reviewed by a mentor? Book a 1:1 mentorship session with The Salesforce Monk, and keep going with our Apex trigger interview questions.

Explore More Blogs

Shubham Samudrawar
Shubham Samudrawar

Shubham Samudrawar is a Senior Salesforce Developer, 6x Salesforce Certified Professional, and Trailhead ⭐⭐⭐Ranger. He is the Founder of The Salesforce Monk, a community-driven platform that helps learners and professionals grow in the Salesforce ecosystem through guided mentorship for real-world success.

Articles: 34

Leave a Reply

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