Sub topic 3
Common Built-in Exception Types
This chapter assumes you can write basic Apex classes and methods, run SOQL queries and DML statements, and read a debug log. It also assumes you know that Apex runs inside a transaction with governor limits. You have seen try, catch, and finally. Now you need to know which exception types to expect, and what usually causes each one.
The exception hierarchy
Every Apex exception is a subclass of the built-in Exception class. Salesforce defines many specific types. Each one tells you what category of failure occurred, so you can handle a query failure differently from a null reference.
The types you will meet most often are:
| Exception type | Typical cause |
|---|---|
| `DmlException` | An `insert`, `update`, `delete`, `undelete`, or `upsert` failed. |
| `QueryException` | A SOQL query assigned to a single sObject returned zero or more than one row. |
| `NullPointerException` | Code called a method or read a field on a `null` reference. |
| `ListException` | A list was used incorrectly, such as reading an index that does not exist. |
| `MathException` | A math operation failed, such as dividing by zero. |
| `TypeException` | A value could not be converted to the requested type. |
| `SObjectException` | Code accessed a field that was not queried or set on an sObject. |
| `LimitException` | A governor limit was exceeded. |
| `CalloutException` | An HTTP or web service callout failed. |
| `JSONException` | JSON could not be parsed or deserialized. |
| `StringException` | A string operation failed, such as an invalid argument. |
| `NoAccessException` | Code tried to access a record or resource it has no access to. |
The list is not complete. These are the ones that cause most real-world failures.
QueryException
A SOQL query assigned to a single sObject must return exactly one row. If it returns none, or more than one, Apex throws a QueryException.
try {
Account a = [SELECT Id FROM Account WHERE Name = 'Does Not Exist' LIMIT 1];
System.debug(a.Id);
} catch (QueryException e) {
System.debug('Query failed: ' + e.getMessage());
} finally {
System.debug('This runs whether or not an exception occurred.');
}LIMIT 1 does not prevent the exception. It only stops a second row from causing one. An empty result still fails. The finally block runs in both cases.
You can avoid the exception by assigning the query to a list and checking its size:
List<Account> matches = [SELECT Id FROM Account WHERE Name = 'Does Not Exist' LIMIT 1];
if (matches.isEmpty()) {
System.debug('No matching account.');
} else {
System.debug(matches[0].Id);
}Prefer the list form when "no rows" is a normal outcome. Use the single-sObject form, with a catch, when a missing record means something is genuinely wrong.
DmlException
A DmlException is thrown when a DML statement fails. Common causes include a missing required field, a validation rule failure, a failed trigger, or a record locked by another transaction.
try {
insert new Account();
} catch (DmlException e) {
for (Integer i = 0; i < e.getNumDml(); i++) {
System.debug(e.getDmlFieldNames(i) + ': ' + e.getDmlMessage(i));
}
}DmlException has extra methods beyond the base ones. A single statement can fail for many records at once, so these methods report details per failed record:
getNumDml()returns the number of failed records.getDmlFieldNames(i)returns the fields involved in failurei.getDmlMessage(i)returns the error message for failurei.
A later chapter covers DML failures in depth. For now, remember that the failure is per record, not per statement.
NullPointerException
This is the most common exception in everyday Apex. It occurs when you call a method or read a field on a variable that holds null.
try {
String name;
Integer len = name.length();
} catch (NullPointerException e) {
System.debug('Null reference: ' + e.getMessage());
}A related trap involves sObject fields. A field you never set is null, so acc.Name.toUpperCase() fails if Name is empty. Check for null before you dereference a value, or use the safe navigation operator:
Account acc = new Account();
String upper = acc.Name?.toUpperCase();
System.debug(upper);The ?. operator returns null instead of throwing when the left side is null.
ListException and other collection errors
Reading a list index that is out of range throws a ListException. Sets and maps behave differently. A map returns null for a missing key and does not throw.
List<Integer> numbers = new List<Integer>{ 1, 2, 3 };
try {
Integer value = numbers[5];
System.debug(value);
} catch (ListException e) {
System.debug('Bad index: ' + e.getMessage());
}Reading numbers[5] on a three-element list fails. Check numbers.size() first, or use isEmpty() before reading numbers[0].
MathException and TypeException
Dividing by zero throws a MathException:
try {
Integer result = 10 / 0;
System.debug(result);
} catch (MathException e) {
System.debug('Math error: ' + e.getMessage());
}A TypeException appears when a conversion fails, for example when you parse text that is not a valid number:
try {
Integer n = Integer.valueOf('abc');
System.debug(n);
} catch (TypeException e) {
System.debug('Conversion failed: ' + e.getMessage());
}Validate input before converting it when the value comes from a user or an external system.
SObjectException
An SObjectException occurs when you read a field that the query did not select. Apex only loads the fields you ask for.
Account a = [SELECT Id FROM Account LIMIT 1];
try {
System.debug(a.Name);
} catch (SObjectException e) {
System.debug('Field not queried: ' + e.getMessage());
}This exception requires at least one Account in the org. The fix is to add the field to the SELECT clause. It is easy to confuse with NullPointerException: here the field was never loaded at all, while a null field was loaded and has no value.
LimitException
When code exceeds a governor limit, Apex throws a System.LimitException. A common example is running a SOQL query inside a loop until you pass the 100-query synchronous limit.
This exception has an unusual property. You cannot catch it. A catch block for LimitException, or for the generic Exception, does not stop the failure. The transaction ends and all changes roll back. A later chapter covers this behavior. The practical lesson is to prevent limit errors by bulkifying code, not to handle them after the fact.
for (Integer i = 0; i < 101; i++) {
try {
List<Account> rows = [SELECT Id FROM Account LIMIT 1];
} catch (Exception e) {
System.debug('This catch will not stop the limit failure.');
}
}Running this in an anonymous Apex window fails on the 101st query, and the catch block does not save the transaction.
CalloutException and JSONException
A CalloutException signals a failed callout. The causes include a timeout, an unreachable endpoint, or a callout attempted after uncommitted DML in the same transaction. A JSONException signals text that does not match the structure you tried to deserialize it into.
try {
Map<String, Object> parsed = (Map<String, Object>) JSON.deserializeUntyped('not json');
System.debug(parsed);
} catch (JSONException e) {
System.debug('Invalid JSON: ' + e.getMessage());
}Choosing which type to catch
Catch the most specific type that you can actually handle. The next chapters cover catch order, but the guideline starts here.
- Catch
QueryExceptionwhen a missing record has a sensible fallback. - Catch
DmlExceptionwhen you can report or recover from a save failure. - Do not catch
NullPointerExceptionto cover for sloppy code. Fix the code with a null check instead. - Catch
CalloutExceptionandJSONExceptionat integration boundaries, where outside systems can fail in ways you do not control.
Exceptions such as NullPointerException, ListException, and MathException usually point to a bug. Fixing the cause is better than catching the symptom.
Common mistakes
- Assuming
LIMIT 1prevents aQueryExceptionon an empty result. - Reading a field that the query did not select and expecting
null. - Treating a missing map key as an error. It returns
nullinstead. - Catching
LimitExceptionand expecting execution to continue. - Catching
NullPointerExceptionin place of adding a null check.
Exercise
A method runs Contact c = [SELECT Id FROM Contact WHERE Email = :addr]; and the email matches two contacts. Which exception is thrown, and how can you rewrite the query to avoid it when you only need to know whether any match exists?
Show answer
A QueryException is thrown, because a query assigned to a single sObject must return exactly one row. Assign the result to a List<Contact> instead, then check isEmpty() or size(). The list form handles zero, one, or many rows without throwing.
Exercise
Code reads acc.Industry.toLowerCase() on an Account that was queried with SELECT Id, Industry FROM Account. The Industry field is empty on that record. Which exception occurs, and which one would occur if Industry had been left out of the SELECT list?
Show answer
A NullPointerException occurs, because the field was loaded and holds null. If Industry were missing from the SELECT list, reading it would throw an SObjectException instead, because the field was never loaded.