Apex : Throwing Custom Exceptions

There will be scenarios when you want to throw an exception from your catch block, may be to propagate to the invoking class so it is handled properly.

Below is a Custom Exception class which can be used to throw different types of exceptions as needed.

public with sharing class CustomExceptions {

public class InputDataException extends Exception {}
public class RequiredException extends Exception {}
public class GovernorLimitException extends Exception {}
public class CommunityException extends Exception{}
public class RecordLockedException extends Exception{}
public class AuthorizationException extends Exception {}

}

From the Apex class: you can use the code below to throw custom exceptions

if( String.isEmpty(case.Analysis__c) ) {
throw new CustomExceptions.RequiredException(‘Analysis is missing from the Case’);
}
else {
throw new CustomExceptions.RequiredException(‘Cases can be assigned by Tier 1 or Admin Users’);
}

Permanent link to this article: https://salesforcebuddy.com/2019/01/apex-throwing-custom-exceptions/

Leave a Reply

Your email address will not be published.