Sub topic 8
Wrapping and rethrowing with a cause
This chapter assumes you can write try, catch, and finally blocks, define a custom exception class, and read the basic exception methods such as getMessage and getTypeName. Here you will learn how to catch a low-level exception, throw a more meaningful one in its place, and keep the original failure attached so you can still diagnose it.
Why wrap an exception
A low-level exception such as DmlException or QueryException describes what the platform did, not what your application was trying to do. A caller of AccountService.create doesn't care that an insert statement failed. It cares that an account could not be created.
Wrapping means catching the low-level exception and throwing a new exception of your own type. That gives you three benefits:
- A stable contract. Callers catch
AccountServiceExceptionand don't depend on which statement the service uses internally. - A clearer message. The new message can describe the business operation that failed.
- A single place to handle failures. A controller or trigger handler can catch one type instead of several.
The danger is that a new exception hides the old one. If you throw a new exception and discard the original, you lose the field names, the error codes, and the stack trace that explain the real problem. The fix is to pass the original exception as the cause.
Passing a cause to a custom exception
Every class that extends Exception automatically gets four constructors:
| Constructor | Use |
|---|---|
| `new MyException()` | No message, no cause |
| `new MyException('text')` | Message only |
| `new MyException(cause)` | Cause only |
| `new MyException('text', cause)` | Message and cause |
You don't declare these constructors. Declaring extends Exception is enough. Prefer the two-argument form, because it gives you a message you control and keeps the original failure.
public class AccountService {
public class AccountServiceException extends Exception {}
public static void create(Account acc) {
try {
insert acc;
} catch (DmlException e) {
throw new AccountServiceException('Could not create account', e);
}
}
}The catch block runs only for DmlException. Any other exception passes through unchanged. The new exception holds a reference to the DmlException as its cause.
Reading the cause
The caller catches the wrapper type and can walk back to the original with getCause(). This method returns the cause as an Exception, or null if none was set.
try {
AccountService.create(new Account());
} catch (AccountService.AccountServiceException e) {
System.debug('Wrapper message: ' + e.getMessage());
Exception cause = e.getCause();
if (cause != null) {
System.debug('Cause type: ' + cause.getTypeName());
System.debug('Cause message: ' + cause.getMessage());
}
}Run this as anonymous Apex with debug logs open. The wrapper message is your own text. The cause message is the platform's text, such as a required-field error for Name.
Getting DML details from the cause
Because getCause() returns the general Exception type, DML-specific methods are not available on it directly. Check the type and cast:
try {
AccountService.create(new Account());
} catch (AccountService.AccountServiceException e) {
if (e.getCause() instanceof DmlException) {
DmlException dml = (DmlException) e.getCause();
for (Integer i = 0; i < dml.getNumDml(); i++) {
System.debug(dml.getDmlFieldNames(i) + ': ' + dml.getDmlMessage(i));
}
}
}The instanceof check protects you from a TypeException if the cause is some other type or is null. (null instanceof DmlException evaluates to false.)
Finding the root cause in a chain
A cause can itself have a cause. A controller might wrap a service exception, which wrapped a DmlException. To reach the original failure, loop until getCause() returns null:
public class ExceptionUtil {
public static Exception rootCause(Exception e) {
Exception current = e;
while (current.getCause() != null) {
current = current.getCause();
}
return current;
}
public static String describeChain(Exception e) {
List<String> lines = new List<String>();
Exception current = e;
while (current != null) {
lines.add(current.getTypeName() + ': ' + current.getMessage());
current = current.getCause();
}
return String.join(lines, '\n caused by ');
}
}describeChain is useful when you log an error. It records every layer in one string, from the outermost wrapper to the root cause.
Rethrowing without wrapping
Sometimes you need to react to a failure but not change its type. The earlier chapters on savepoints showed this pattern: clean up, then throw the same exception object again.
Savepoint sp = Database.setSavepoint();
try {
Account acc = new Account(Name = 'Parent');
insert acc;
insert new Contact(AccountId = acc.Id);
} catch (DmlException e) {
Database.rollback(sp);
throw e;
}throw e; rethrows the same object, so its type, message, and stack trace stay as they were. This differs from wrapping in a way that matters for diagnosis:
- A rethrown exception keeps the stack trace from where it was first thrown.
- A wrapper exception has its own stack trace, which starts where you created it. The original stack trace remains available through
getCause().getStackTraceString().
If you need both a cleanup step and a stable type for callers, do both. Roll back, then throw the wrapper with the cause.
Choosing between rethrow, wrap, and propagate
| Situation | Choice |
|---|---|
| Nothing useful to do at this layer | Don't catch. Let it propagate. |
| You must clean up, but the type is already meaningful | Catch and rethrow with `throw e;` |
| The type exposes internal details, or the layer needs its own contract | Wrap with a message and the cause |
| You can fully recover (retry, use a default value) | Catch and handle. Don't rethrow. |
A good rule is to wrap at a layer boundary, such as between a service class and a controller, and nowhere else. Wrapping at every method call buries the real problem under a deep chain of near-identical messages.
Common mistakes
- Dropping the cause.
throw new AccountServiceException('Could not create account');compiles and runs, but the platform's explanation is gone. Always passeas the second argument. - Copying the message instead of the cause.
new AccountServiceException(e.getMessage())keeps the text but loses the type, the DML details, and the stack trace. - Catching
Exceptionto wrap everything. A broad catch also wraps your own validation exceptions, so they end up wrapped inside a generic one. Catch the specific types you expect. - Expecting to wrap limit exceptions. Governor limit exceptions can't be caught, so they never reach your
catchblock. Wrapping does not help there. - Assuming the cause crosses to a Lightning component. When you throw
AuraHandledException, only its message reaches the client. Log the chain on the server with something likedescribeChain, and put a user-readable message on the Aura exception.
Testing a wrapper
@IsTest
private class AccountServiceTest {
@IsTest
static void wrapsDmlExceptionWithCause() {
try {
AccountService.create(new Account());
Assert.fail('Expected AccountServiceException was not thrown');
} catch (AccountService.AccountServiceException e) {
Assert.isTrue(e.getMessage().contains('Could not create account'));
Assert.isNotNull(e.getCause(), 'Cause should be preserved');
Assert.isTrue(e.getCause() instanceof DmlException);
}
}
}Assert.fail throws an AssertException. The catch block does not match that type, so the test fails if the service never throws.
Exercise
A service method catches QueryException and runs throw new ReportException('Report data unavailable');. A developer later sees only that message in the logs and cannot tell which query failed. What change fixes this, and why does the original QueryException stack trace still matter?
Show answer
Pass the caught exception as the second constructor argument: throw new ReportException('Report data unavailable', e);. The wrapper then keeps the QueryException as its cause. The wrapper's own stack trace starts where the wrapper was created, while e.getStackTraceString() on the cause points to the line where the query failed. Logging the chain, for example with a helper that walks getCause(), shows both.
Exercise
Write a loop that finds the root cause of an exception variable named ex, and say what it returns when ex has no cause.
Show answer
Exception current = ex; while (current.getCause() != null) { current = current.getCause(); }. When ex.getCause() is null, the loop never runs and current is ex itself, so the root cause is the exception you started with.