Apex Exception Handling
What is an Exception?
An exception means something went wrong when your code was running.
Imagine you’re using a calculator, and you try to divide a number by zero. That’s not allowed, so it gives an error. That error is called an exception.
In programming (like in Apex), exceptions can happen when:
• A value is missing (null)
• A number is wrong
• A record isn’t found
• You try to do something not allowed
 
															Why Do Exceptions Matter?
What is Exception Handling?
Exception Handling means:
• Catching the error
• Responding to it properly (like showing a message or skipping the error)
• So the rest of the code can keep working smoothly
Common Exceptions:
| Exception Type | When It Happens | 
|---|---|
| DmlException | Errors during insert/update/delete | 
| NullPointerException | Accessing null variables | 
| QueryException | SOQL query fails or returns nothing | 
| ListException | Accessing wrong index in a list | 
| MathException | Division by zero or invalid math | 
Apex Exception Handling Syntax :
try { // Code that might throw an exception } catch (ExceptionType e) { // Code to handle the exception System.debug(‘Error: ‘ + e.getMessage()); } finally { // (Optional) Code that runs no matter what — success or error }
Common Exceptions:
| Part | Description | 
|---|---|
| try | Write the code here that might cause an error | 
| catch | If an error happens in the try, the catch will handle it | 
| ExceptionType | This is the type of error, like DmlException, NullPointerException, etc. | 
| e.getMessage() | This gets the error message and helps in debugging/logging | 
| finally | (Optional) This block always runs — even if an error occurs or not | 
Example 1: Handling DML Exception (Insert Error)
try {
Account acc = new Account(); // Missing required ‘Name’
insert acc;
} catch (DmlException e) {
System.debug(‘DML Error: ‘ + e.getMessage());
}
Explanation :
• We are trying to insert an Account without the required field Name.
• This causes a DML Exception.
• The catch block handles the error and logs the message instead of crashing.
Example 2: Handling NullPointerException
try {
String email;
Integer len = email.length(); // Trying to get length of null
} catch (NullPointerException e) {
System.debug(‘Error: You tried to use something that is null.’);
}
Explanation :
• email is null, and calling .length() causes an error.
• This is a NullPointerException.
• We catch the error and print a user-friendly message.
Example 3: Handling SOQL Query Exception
try {
Contact c = [SELECT Name FROM Contact WHERE Email = ‘abc@example.com’ LIMIT 1];
System.debug(‘Contact Found: ‘ + c.Name);
} catch (QueryException e) {
System.debug(‘No contact found or query failed.’);
}
Explanation :
• If no contact with that email exists, the query throws a QueryException.
• This is caught and a message is logged.
Example 4: Handling List Index Exception
try {
List<String> fruits = new List<String>{‘Apple’, ‘Banana’};
System.debug(fruits[3]); // Index out of range
} catch (ListException e) {
System.debug(‘Error: You tried to access a list item that doesn’t exist.’);
}
Explanation :
• The list only has 2 items, but we tried to get item at index 3.
• This causes a ListException, which we catch and handle.
Example 5: Handling Division by Zero (MathException)
try {
Integer a = 10;
Integer b = 0;
Integer result = a / b; // Error: divide by 0
} catch (MathException e) {
System.debug(‘You cannot divide a number by zero!’);
}
Explanation :
• Dividing a number by zero causes a MathException.
• We catch it and print a friendly error message.





