Curriculum
Exception Handling is a critical programming technique used to manage runtime errors and unexpected situations in Apex applications. Instead of allowing a program to terminate abruptly when an error occurs, Exception Handling enables developers to detect errors, respond appropriately, maintain application stability, and provide meaningful feedback to users.
In Salesforce development, exceptions can occur during database operations, integrations, record processing, calculations, API calls, file operations, and user interactions. Proper Exception Handling ensures that applications remain reliable, secure, and user-friendly even when unexpected issues arise.
Understanding Exception Handling is essential for Salesforce Developers because robust error management is a key requirement for enterprise-grade applications.
An Exception is an error or unexpected event that occurs during program execution.
Examples:
Exceptions interrupt the normal flow of execution.
Without Exception Handling:
Exception Handling helps applications respond gracefully to errors.
Prevent application crashes.
Display meaningful messages.
Capture detailed error information.
Protect business data.
Handle unexpected situations safely.
These benefits make Exception Handling essential in Apex development.
Exceptions commonly occur due to:
Developers should anticipate and handle these scenarios.
Integer result = 10 / 0;
Output:
System.MathException:
Division by 0
The application generates an exception because division by zero is not allowed.
Exception Handling is the process of detecting and managing runtime errors.
Apex provides:
These constructs help manage exceptions effectively.
The try block contains code that may generate exceptions.
Syntax:
try{
// risky code
}
If an exception occurs, control transfers to the catch block.
try{
Integer result = 10 / 0;
}
catch(Exception e){
System.debug(e);
}
The exception is handled instead of crashing the application.
The catch block handles exceptions generated inside the try block.
Syntax:
catch(Exception e){
}
The exception object contains error details.
try{
Integer result = 10 / 0;
}
catch(Exception e){
System.debug(
e.getMessage()
);
}
Output:
Division by 0
The error is captured and processed safely.
The exception object provides information about the error.
Example:
Exception e
Useful methods include:
These methods assist with debugging.
Returns the error description.
Example:
System.debug(
e.getMessage()
);
Output:
Division by 0
Useful for user-friendly error messages.
Returns the line number where the error occurred.
Example:
System.debug(
e.getLineNumber()
);
Output:
15
Developers use this during troubleshooting.
Returns the exception type.
Example:
System.debug(
e.getTypeName()
);
Output:
System.MathException
Helps identify error categories.
The finally block executes regardless of whether an exception occurs.
Syntax:
try{
}
catch(Exception e){
}
finally{
}
Useful for cleanup activities.
try{
Integer result = 10 / 0;
}
catch(Exception e){
System.debug('Error');
}
finally{
System.debug(
'Execution Complete'
);
}
Output:
Error
Execution Complete
The finally block always executes.
Execute try block.
If no exception occurs:
Continue normally.
If exception occurs:
Transfer control to catch block.
Execute finally block.
This process ensures controlled error handling.
Occurs during DML operations.
Example:
Account acc =
new Account();
insert acc;
Output:
Required fields missing
The record cannot be inserted.
try{
insert acc;
}
catch(DmlException e){
System.debug(
e.getMessage()
);
}
The error is handled safely.
Occurs when SOQL queries fail.
Example:
Account acc = [
SELECT Name
FROM Account
WHERE Id = 'XYZ'
];
Invalid queries may generate exceptions.
try{
Account acc = [
SELECT Name
FROM Account
LIMIT 1
];
}
catch(QueryException e){
System.debug(
e.getMessage()
);
}
Useful for record retrieval operations.
Occurs when accessing a null object.
Example:
String courseName = null;
System.debug(
courseName.length()
);
Output:
Attempt to de-reference a null object
This is one of the most common Apex errors.
if(courseName != null){
System.debug(
courseName.length()
);
}
Null checking prevents exceptions.
Occurs during invalid mathematical operations.
Example:
Integer result =
10 / 0;
Output:
Division by 0
Proper validation helps avoid these errors.
Occurs when invalid list operations are performed.
Example:
List<String> courses =
new List<String>();
System.debug(
courses[0]
);
Output:
List index out of bounds
Developers should verify list size before access.
if(courses.size() > 0){
System.debug(
courses[0]
);
}
Validation improves application stability.
Apex allows handling different exception types.
Example:
try{
}
catch(DmlException e){
}
catch(QueryException e){
}
catch(Exception e){
}
This provides specialized error handling.
The throw keyword generates an exception manually.
Example:
throw new Exception(
'Invalid Student Data'
);
Useful for custom validation logic.
Custom Exceptions are developer-defined exception classes.
Example:
public class StudentException
extends Exception{
}
Custom Exceptions improve business-specific error handling.
public class StudentException
extends Exception{
}
Usage:
throw new StudentException(
'Student Not Found'
);
Provides meaningful error information.
Example:
try{
insert students;
}
catch(DmlException e){
System.debug(
'Insert Failed'
);
}
Widely used in Salesforce applications.
External API calls may fail.
Example:
Exception Handling ensures reliable integrations.
Developers should log errors for analysis.
Example:
System.debug(
e.getMessage()
);
Logs help identify root causes.
Improve clarity.
Always handle errors.
Support troubleshooting.
Prevent errors.
Improve business logic.
Improve user experience.
These practices improve application reliability.
Developers should avoid these issues.
A software training company processes enrollments.
try{
Student__c student =
new Student__c();
insert student;
}
catch(DmlException e){
System.debug(
'Enrollment Failed'
);
}
This prevents application failure when invalid student data is submitted.
Understanding Exception Handling helps professionals:
Exception Handling is a core Apex development skill.
Exception Handling is the process of managing runtime errors in Apex applications. Through try, catch, and finally blocks, developers can detect errors, handle exceptions gracefully, maintain application stability, and improve user experience. Apex supports several exception types including DmlException, QueryException, NullPointerException, MathException, and ListException. Mastering Exception Handling is essential for building reliable, scalable, and enterprise-grade Salesforce applications.
An Exception is a runtime error that interrupts normal program execution.
Exception Handling is the process of detecting and managing runtime errors.
The try block contains code that may generate exceptions.
A catch block handles exceptions generated in the try block.
A finally block executes regardless of whether an exception occurs.
It improves application stability, reliability, and user experience.
Looking to learn more technologies and programming skills?
Send us your inquiry and start your journey towards a successful IT career.
✔ 100% Secure ✔ No Spam ✔ Instant Response
WhatsApp us