Exception Handling & Error Management in Apex
try / catch / finally
What Is Exception Handling?
Exception handling lets your code handle errors gracefully instead of crashing.
Simple Explanation
It’s like a seatbelt—you hope you won’t need it, but it protects you when something goes wrong.
Real-Life Example
If an ATM transaction fails, you get a message—not a system crash.
Basic Structure
try {
// risky code
} catch (Exception e) {
// handle error
} finally {
// always runs
}
Code Example
try {
Integer result = 10 / 0; // error
} catch (Exception e) {
System.debug('Error occurred: ' + e.getMessage());
} finally {
System.debug('Execution completed');
}
Key Points
-
try→ code that might fail -
catch→ handles the error -
finally→ runs no matter what
Gist (Quick Revision)
Use try/catch/finally to prevent system crashes and control failures safely.
2. Custom Exceptions
What Is a Custom Exception?
A custom exception lets you create your own error messages for business rules.
Simple Explanation
Built-in errors are technical; custom errors are business-friendly.
Real-Life Example
“You cannot withdraw more than your balance”
instead of
“Unhandled exception occurred”
Code Example
public class InsufficientBalanceException extends Exception {}
if (balance < amount) {
throw new InsufficientBalanceException('Not enough balance');
}
Why Custom Exceptions Matter
-
Clear business errors
-
Easier debugging
-
Better user experience
Gist (Quick Revision)
Custom exceptions make errors meaningful and business-friendly.
3. Safe Error Handling Patterns (Best Practices)
Pattern 1: Never Expose System Errors to Users
❌ Bad
throw e;
✅ Good
throw new AuraHandledException('Something went wrong. Please contact support.');
Pattern 2: Log Errors, Don’t Ignore Them
System.debug('Error: ' + e.getMessage());
(Advanced projects use custom logging frameworks.)
Pattern 3: Fail Gracefully
-
Stop only the failed operation
-
Allow remaining logic to continue when possible
Pattern 4: Handle DML Exceptions Properly
try {
insert acc;
} catch (DmlException e) {
System.debug(e.getDmlMessage(0));
}
Career Coach Insight
Interviewers look for developers who:
-
Handle errors responsibly
-
Protect user experience
-
Avoid exposing sensitive system details
Production code must fail safely, not loudly.
Gist (Quick Revision)
Good error handling protects users, helps debugging, and keeps systems stable.
