Sub topic 2
Throwing Exceptions Deliberately
Assume you know basic Apex classes, methods, SOQL, DML, and governor limits. An exception is an object that signals a failure. If no matching catch block handles it, Apex stops the current operation and propagates the exception to the caller.
Throwing an exception
Use throw when a method detects invalid input or cannot complete its contract. A clear message helps callers and logs explain the failure.
public class InvoiceService {
public class InvoiceException extends Exception {}
public static Decimal applyDiscount(Decimal amount, Decimal percent) {
if (percent < 0 || percent > 100) {
throw new InvoiceException(
'Discount must be between 0 and 100: ' + percent
);
}
return amount - (amount * percent / 100);
}
}A custom exception is a class that extends Exception. Its name conventionally ends with Exception. Define it inside the service when the error belongs only to that service, or in a shared class when several services use it.
Wrapping and rethrowing with a cause
A lower-level exception contains useful technical details, but exposing it directly can couple callers to implementation details. Wrap it in a domain-specific exception and preserve the original as its cause.
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
);
}
}
}Callers can inspect getMessage(), getTypeName(), getCause(), and getStackTraceString() while responding to the stable service exception type.
Handling DML failures
A single-record DML statement throws DmlException when it fails. Use its DML-specific methods to inspect each failed operation.
try {
insert new Account();
} catch (DmlException e) {
for (Integer i = 0; i < e.getNumDml(); i++) {
System.debug(e.getDmlFieldNames(i) + ': ' + e.getDmlMessage(i));
}
}For a list, Database.insert(records, false) reports failures in SaveResult objects and can save valid records. Choose this partial-success behavior deliberately because the transaction may contain both committed and failed records.
Exercise
Why should a service wrap a DmlException instead of always rethrowing it directly?
Show answer
Wrapping gives callers a stable, meaningful service-level type and message while preserving the original exception as the cause for diagnosis.