Sub topic 5
Multiple catch blocks and the generic Exception
This chapter assumes you can write a basic try/catch/finally block and that you know the common built-in exception types, such as DmlException, QueryException, and NullPointerException. It covers how Apex chooses between several catch blocks, why the generic Exception block goes last, and when a generic catch helps or hurts.
How Apex picks a catch block
A try block can be followed by any number of catch blocks. When code inside the try throws an exception, Apex checks the catch blocks from top to bottom. It runs the first block whose exception type matches the thrown exception. A block matches when the thrown exception is an instance of the declared type, or of a subclass of it. Apex skips all remaining catch blocks and then runs finally, if there is one.
Three consequences follow from this:
- At most one
catchblock runs for a given exception. - An exception thrown inside a
catchblock is not handled by the siblingcatchblocks of the sametry. It propagates outward, afterfinallyruns. - If no block matches, the exception keeps propagating. The
finallyblock still runs first.
A first example with specific blocks
Each catch declares its own variable, so you can reuse the name e in every block.
try {
Account a = [SELECT Id, Name FROM Account WHERE Name = 'Does Not Exist' LIMIT 1];
a.Name = a.Name + ' Updated';
update a;
} catch (QueryException e) {
System.debug('No matching account: ' + e.getMessage());
} catch (DmlException e) {
System.debug('Update failed: ' + e.getDmlMessage(0));
} catch (Exception e) {
System.debug('Unexpected ' + e.getTypeName() + ': ' + e.getMessage());
} finally {
System.debug('Cleanup runs in every case.');
}The query returns no rows, so assigning the result to a single Account throws a QueryException. The first block handles it. The DmlException block and the generic block are skipped, and finally still runs.
The generic Exception goes last
Exception is the base type of every Apex exception, built-in or custom. A catch (Exception e) block therefore matches almost anything. Apex requires the generic Exception block to be the last catch block. If you put it first, the code does not compile, because the specific blocks after it could never run.
Built-in types such as DmlException, QueryException, and MathException extend Exception directly. They do not extend each other, so their order relative to one another does not matter. Order matters when your own exceptions form a hierarchy.
Seeing each branch run
The class below triggers three different built-in exceptions depending on its argument. You can call it from Anonymous Apex to see which block runs.
public class CatchDemo {
public static String run(Integer mode) {
try {
if (mode == 1) {
insert new Account(); // Name is required
} else if (mode == 2) {
Integer zero = 0;
Integer result = 1 / zero;
} else if (mode == 3) {
String s = null;
s.length();
}
return 'No exception';
} catch (DmlException e) {
return 'DmlException: ' + e.getDmlMessage(0);
} catch (MathException e) {
return 'MathException: ' + e.getMessage();
} catch (Exception e) {
return 'Generic catch got ' + e.getTypeName();
}
}
}Run this in Anonymous Apex:
for (Integer i = 0; i <= 3; i++) {
System.debug(i + ' -> ' + CatchDemo.run(i));
}Modes 1 and 2 are handled by the specific blocks. Mode 3 throws a NullPointerException, which has no dedicated block, so the generic block handles it. getTypeName() returns System.NullPointerException, so you can still tell what happened.
Order matters with custom hierarchies
Custom exceptions can extend other custom exceptions. A catch for the parent type also matches every child, so list the child first.
public class PaymentService {
public virtual class PaymentException extends Exception {}
public class CardDeclinedException extends PaymentException {}
public static String charge(Decimal amount, Boolean declined) {
try {
if (declined) {
throw new CardDeclinedException('Card declined for ' + amount);
}
if (amount <= 0) {
throw new PaymentException('Amount must be positive');
}
return 'Charged ' + amount;
} catch (CardDeclinedException e) {
return 'Ask the customer for another card';
} catch (PaymentException e) {
return 'Payment problem: ' + e.getMessage();
}
}
}Both exception classes are inner classes, and the parent is declared virtual so that the child can extend it. If the PaymentException block came first, it would catch declined cards too, and the CardDeclinedException block would never run. Always put the narrowest type first and the widest last.
What the generic catch does not catch
catch (Exception e) does not stop everything. Some failures end the transaction no matter what your code does:
- Governor limit violations such as
System.LimitException(too many SOQL queries, too much CPU time) cannot be caught. A generic catch block does not run for them. - Exceptions thrown from code that has already used up a limit still count against that limit. Catching them does not give the budget back.
Because of this, a generic catch is not a guarantee that your method will finish. Write code that stays inside limits instead of relying on catching them.
When a generic catch is appropriate
Use catch (Exception e) deliberately, in these situations:
- At a boundary. An
@AuraEnabledmethod, a REST resource, or theexecutemethod of a job can catch everything, log it, and convert it into a form the caller understands. - As a last block after specific ones. The specific blocks handle the cases you planned for, and the generic block records or rethrows anything else.
- For cleanup that must see all failures. You can undo partial work and then rethrow.
A generic block that only logs and then continues is risky. The caller assumes the work succeeded, and the data may be half-written. Prefer to rethrow, wrap, or return an explicit failure.
Branching inside a generic block
Sometimes you want one block that handles several types differently. Use instanceof on the caught exception:
public class ErrorTranslator {
public static String toUserMessage(Exception e) {
if (e instanceof DmlException) {
return 'Save failed: ' + ((DmlException) e).getDmlMessage(0);
} else if (e instanceof QueryException) {
return 'We could not find the record you asked for.';
}
return 'Unexpected error (' + e.getTypeName() + ')';
}
}This keeps the message-building logic in one place, so several catch blocks, or one generic block, can call it:
try {
insert new Contact(); // LastName is required
} catch (Exception e) {
System.debug(ErrorTranslator.toUserMessage(e));
throw e; // do not hide the failure from the caller
}Rethrowing with throw e; keeps the original exception and its stack trace. Wrapping it in a new exception, with the original as the cause, is covered in a later chapter.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Generic `Exception` block placed before specific blocks | Compile error | Put `catch (Exception e)` last |
| Parent custom exception caught before its child | The child block never runs | List child types first |
| Empty `catch (Exception e) {}` | Failures disappear silently | Log, rethrow, or return an error |
| Expecting the generic block to catch limit errors | The transaction still ends | Bulkify and check limits with the `Limits` class |
| Doing risky work inside a `catch` block | The new exception escapes the `try` statement | Keep catch bodies short, or nest a `try` inside them |
Exercise
A method contains a try block followed by catch (Exception e), then catch (DmlException e). What happens, and how do you fix it? Then, for a try block with catch (PaymentException e) followed by catch (CardDeclinedException e), where CardDeclinedException extends PaymentException, which block handles a thrown CardDeclinedException?
Show answer
The first case does not compile, because the generic Exception block must be the last catch block. Move catch (DmlException e) above it. In the second case, the PaymentException block handles it. A catch for a parent type matches all of its subclasses, so the CardDeclinedException block can never run. Swap the order so the child type comes first.
Exercise
Why can't catch (Exception e) protect a method from a System.LimitException caused by too many SOQL queries, and what should you do instead?
Show answer
Governor limit exceptions cannot be caught, so the generic block does not run and the transaction ends. Prevent them instead: bulkify the code, move queries out of loops, and use the Limits class to check remaining capacity before doing expensive work.