Try, Catch, and Finally
By the end of this lesson, you'll be able to:
- Write a try/catch block to handle a runtime exception without crashing
- Explain what code inside finally guarantees
- Recognize the difference between an exception being thrown and being handled
Prerequisites: "ApexDoc and Documentation Standards"
Catching an exception
Decimal result;
try {
result = 10 / 0;
} catch (MathException e) {
System.debug('Caught a math error: ' + e.getMessage());
result = 0;
}
System.debug('Continuing normally: ' + result);
Without try/catch, 10 / 0 would throw a MathException and immediately stop the whole transaction (as seen back in Module 8). Wrapping it in try lets catch step in, handle the problem, and let execution continue normally afterward — 'Continuing normally' still prints.
finally always runs
try {
Decimal result = 10 / 0;
} catch (MathException e) {
System.debug('Handled: ' + e.getMessage());
} finally {
System.debug('This always runs, error or not.');
}
The finally block runs whether the try succeeded, failed and got caught, or even failed in a way nothing caught — it's the right place for cleanup that must always happen regardless of outcome, like closing a resource or logging that an operation finished.
A real business example: Order Processing
public String processOrder(Decimal orderTotal, Decimal discountPercent) {
try {
Decimal discount = orderTotal * (discountPercent / 100);
return 'Order total after discount: ' + (orderTotal - discount);
} catch (Exception e) {
System.debug('Failed to process order: ' + e.getMessage());
return 'Order could not be processed.';
} finally {
System.debug('Order processing attempt finished at ' + System.now());
}
}
An order-processing method that might fail for any number of reasons returns a sensible fallback message instead of crashing — while finally logs that the attempt happened, successful or not, useful for auditing.
Exercise
Write a try/catch that attempts Decimal result = 20 / 0, catches MathException, debugs "Division failed", and uses finally to debug "Attempt complete".
Show hint
try { ... } catch (MathException e) { ... } finally { ... }
Try, Catch, and Finally Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
try/catch lets code recover from a runtime error instead of crashing the whole transaction; finally guarantees a block of cleanup code runs no matter what happened in the try.