Exception Class and Built-In Exceptions

An exception denotes an error that disrupts the normal flow of code execution. You can use Apex built-in exceptions or create custom exceptions. All exceptions have common methods.

All exceptions support built-in methods for returning the error message and exception type. In addition to the standard exception class, there are several different types of exceptions:

The following are exceptions in the System namespace.

ExceptionDescription
AssertExceptionA System.assert failure that halts code execution. Optionally contains the custom message specified in the last (msg) argument to the assert() method.
AuraExceptionLegacy Aura-related exception. Use System.AuraHandledException instead.
AuraHandledExceptionReturns a custom error message to a JavaScript controller. See Returning Errors from an Apex Server-Side Controller.
AsyncExceptionAny problem with an asynchronous operation, such as failing to enqueue an asynchronous call.
BigObjectExceptionAny problem with big object records, such as connection timeouts during attempts to access or insert big object records.
CalloutExceptionAny problem with a web service operation, such as failing to make a callout to an external system.
DataWeaveScriptExceptionAny run-time script errors that occur within DataWeave in Apex.
DmlExceptionAny problem with a DML statement, such as an insert statement missing a required field on a record.
DuplicateMessageExceptionAttempt to enqueue job with duplicate queueable signature
EmailExceptionAny problem with email, such as failure to deliver. For more information, see Outbound Email.
ExternalObjectExceptionAny problem with external object records, such as connection timeouts during attempts to access the data that’s stored on external systems.
FatalCursorExceptionAny problem with Apex cursors in a transaction.
FinalExceptionAny attempt to mutate a read-only collection or record such as an sObject in an after-update trigger, or a final variable. This exception causes execution to halt.
FlowExceptionAny problem with starting flow interviews from Apex. For example, if an active version of the flow can’t be found or it can’t be started from Apex.
HandledExceptionA generic handled exception.
IllegalArgumentExceptionAn illegal argument was provided to a method call. For example, a method that requires a non-null argument throws this exception if a null value is passed into the method.
InvalidHeaderExceptionAn illegal header argument was provided to an Apex REST call. For example, a call to the RestResponse.addHeader(name, value) method throws this exception if the header name is cookie.
InvalidParameterValueExceptionThis exception is used with both Visualforce pages and Salesforce Functions.
  • Visualforce: The exception is thrown when an invalid parameter is supplied for a method, or any problem is encountered with a URL used with Visualforce pages. For more information on Visualforce, see the Visualforce Developer’s Guide.
  • Salesforce Functions: The exception is thrown when the functionName parameter to Function.get() doesn’t have the correct project name.function name format. For more information on Salesforce functions, see Function.get().
LimitExceptionA governor limit has been exceeded. This exception can’t be caught.
JSONExceptionAny problem with JSON serialization and deserialization operations. For more information, see the methods of System.JSON, System.JSONParser, and System.JSONGenerator.
ListExceptionAny problem with a list, such as attempting to access an index that is out of bounds.
MathExceptionAny problem with a mathematical operation, such as dividing by zero.
NoAccessExceptionAny problem with unauthorized access, such as trying to access an sObject that the current user doesn’t have access to. This exception is used with Visualforce pages. For more information on Visualforce, see the Visualforce Developer Guide.
NoDataFoundExceptionThis exception is used with both Visualforce pages and Salesforce Functions.
  • Visualforce: The exception is thrown with data that doesn’t exist, such as trying to access an sObject that has been deleted. For more information on Visualforce, see the Visualforce Developer’s Guide.
  • Salesforce Functions: The exception is thrown when the project or function name provided in the functionName parameter to the Function.get() method can’t be found. For more information on Salesforce functions, see Function.get().
NoSuchElementExceptionThis exception is thrown if you try to access items that are outside the bounds of a list. This exception is used by the Iterator next method. For example, if iterator.hasNext() == false and you call iterator.next(), this exception is thrown. This exception is also used by the Apex Flex Queue methods and is thrown if you attempt to access a job at an invalid position in the flex queue.
NullPointerExceptionAny problem with dereferencing null. For an example, see NullPointerException Example.
QueryExceptionAny problem with SOQL queries, such as assigning a query that returns no records or more than one record to a singleton sObject variable.
RequiredFeatureMissingA Chatter feature is required for code that has been deployed to an organization that doesn’t have Chatter enabled.
SearchExceptionAny problem with SOSL queries executed with SOAP API search() call, for example, when the searchString parameter contains fewer than two characters. For more information, see the SOAP API Developer Guide.
SecurityExceptionAny problem with static methods in the Crypto utility class. For more information, see Crypto Class.
SerializationExceptionAny problem with the serialization of data. This exception is used with Visualforce pages. For more information on Visualforce, see the Visualforce Developer Guide.
SObjectExceptionAny problem with sObject records, such as attempting to change a field in an update statement that can only be changed during insert.
StringExceptionAny problem with Strings, such as a String that is exceeding your heap size.
TransientCursorExceptionA transient problem with an Apex cursor transaction. The failed transaction can be retried.
TypeExceptionAny problem with type conversions, such as attempting to convert the String ‘a’ to an Integer using the valueOf method.
UnexpectedExceptionA non-recoverable internal error within Salesforce has occurred. This exception causes execution to halt. If necessary, contact Salesforce Customer Support for more information.
VisualforceExceptionAny problem with a Visualforce page. For more information on Visualforce, see the Visualforce Developer Guide.
XmlExceptionAny problem with the XmlStream classes, such as failing to read or write XML.

The following is an example using the DmlException exception:

For exceptions in other namespaces, see:

Exception methods are all called by and operate on an instance of an exception. This table describes all instance exception methods. All types of exceptions have these methods in common.

NameArgumentsReturn TypeDescription
getCause ExceptionReturns the cause of the exception as an exception object.
getLineNumber IntegerReturns the line number from where the exception was thrown.
getMessage StringReturns the error message that displays for the user.
getStackTraceString StringReturns the stack trace of a thrown exception as a string.
getTypeName StringReturns the type of exception, such as DmlException, ListException, MathException, and so on.
initCauseException causeVoidSets the cause for this exception, if one hasn’t already been set.
setMessageString sVoidSets the error message that displays for the user.

In addition to the common exception methods, DMLException and EmailException have these methods:

NameArgumentsReturn TypeDescription
getDmlFieldNamesInteger iString []Returns the names of the field or fields that caused the error described by the ith failed row.
getDmlFieldsInteger iSchema.sObjectField []Returns the field token or tokens for the field or fields that caused the error described by the ith failed row. For more information on field tokens, see Dynamic Apex.
getDmlIdInteger iStringReturns the ID of the failed record that caused the error described by the ith failed row.
getDmlIndexInteger iIntegerReturns the original row position of the ith failed row.
getDmlMessageInteger iStringReturns the user message for the ith failed row.
getDmlStatusCodeInteger iStringDeprecated. Use getDmlType instead. Returns the Apex failure code for the ith failed row.
getDmlTypeInteger iSystem.StatusCodeReturns the value of the System.StatusCode enum. For an example, see getDmlType Example.
For more information about System.StatusCode, see Enums.
getNumDml IntegerReturns the number of failed rows for DML exceptions.

In addition to the common exception methods, QueryException has this method.

NameArgumentsReturn TypeDescription
getInaccessibleFields Map<String,Set<String>>Returns a map in which each key is an sObjectType and its corresponding value is the set of inaccessible field names in fully qualified format (Namespace__FieldName__c).
Use this method to determine the cause of the QueryException. The returned map contains data only if the method that threw the QueryException is running in user mode.
For an example, see getInaccessibleFields Example.

In this code sample, it’s assumed that the user doesn’t have field level security access to the Contact.Email and Account.Website fields.