In Apex Exception are handles using try, catch and finally.
try – block of code where an error can occur.
catch – block handles particular type of exception. A single try block can have zero or more exception block. Each catch block must have unique exception type. Once a particular exception type is caught is one catch block, the remaining catch block will not execute.
finally – this block of code execute always and used for clean up code or sending email. A try block can have zero or one finally block.
try { // Try block ***Code Block*** } catch (exceptionType variableName) { // Initial catch block. // At least the catch block or the finally block must be present. code_block } catch (Exception e) { // Optional additional catch statement for other exception types. // Note that the general exception type, 'Exception', // must be the last catch block when it is used. code_block } finally { // Finally block. // At least the catch block or the finally block must be present. code_block }
At least a catch block or a finally block must be present for a try block. catch block is not mandatory for a try block.
Below syntax both are valid and will work fine –
Try-Catch Block
try {
***code_block***
} catch (exceptionType variableName) {
code_block
}
// Optional additional catch blocks
Try-Finally Block
try {
***code_block***
} finally {
code_block
}
The finally block always executes regardless of exception is thrown, and even if no exception is thrown. Finally block executed after the exception caught.
Built-In Exceptions
Apex provides a different type of built-in exception types that the runtime engine throws if errors are encountered during execution. All exceptions support built-in methods for returning the error message and exception type.
Exception | Description |
---|---|
AsyncException | Any problem with an asynchronous operation, such as failing to enqueue an asynchronous call. |
CalloutException | Any problem with a Web service operation, such as failing to make a callout to an external system. |
DmlException | Any problem with a DML statement, such as an insert statement missing a required field on a record. |
EmailException | Any problem with email, such as failure to deliver. For more information, see Outbound Email. |
ExternalObjectException | Any problem with external object records, such as connection timeouts during attempts to access the data that’s stored on external systems. |
InvalidParameterValueException | An invalid parameter was supplied for a method or any problem with a URL used with Visualforce pages. For more information on Visualforce, see the Visualforce Developer’s Guide. |
LimitException | A governor limit has been exceeded. This exception can’t be caught. |
JSONException | Any problem with JSON serialization and deserialization operations. For more information, see the methods of System.JSON, System.JSONParser, andSystem.JSONGenerator. |
ListException | Any problem with a list, such as attempting to access an index that is out of bounds. |
MathException | Any problem with a mathematical operation, such as dividing by zero. |
NoAccessException | Any problem with unauthorized access, such as trying to access an sObject that the current user does not have access to. This is generally used with Visualforce pages. For more information on Visualforce, see the Visualforce Developer’s Guide. |
NoDataFoundException | Any problem with data that does not exist, such as trying to access an sObject that has been deleted. This is generally used with Visualforce pages. For more information on Visualforce, see the Visualforce Developer’s Guide. |
NoSuchElementException | This 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, ifiterator.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. |
NullPointerException | Any problem with dereferencing null, such as in the following code:
String s; |
Any problem with SOQL queries, such as assigning a query that returns no records or more than one record to a singleton sObject variable. | |
RequiredFeatureMissing | A Chatter feature is required for code that has been deployed to an organization that does not have Chatter enabled. |
SearchException | Any problem with SOSL queries executed with SOAP API search() call, for example, when the searchString parameter contains less than two characters. For more information, see the SOAP API Developer Guide. |
SecurityException | Any problem with static methods in the Crypto utility class. For more information, see Crypto Class. |
SerializationException | Any problem with the serialization of data. This is generally used with Visualforce pages. For more information on Visualforce, see the Visualforce Developer’s Guide. |
SObjectException | Any problem with sObject records, such as attempting to change a field in an updatestatement that can only be changed during insert. |
StringException | Any problem with Strings, such as a String that is exceeding your heap size. |
TypeException | Any problem with type conversions, such as attempting to convert the String ‘a’ to an Integer using the valueOf method. |
VisualforceException | Any problem with a Visualforce page. For more information on Visualforce, see the Visualforce Developer’s Guide. |
XmlException | Any problem with the XmlStream classes, such as failing to read or write XML. |
Exception Methods
Name | Return Type | Description |
---|---|---|
getCause | Exception | Returns the cause of the exception as an exception object. |
getLineNumber | Integer | Returns the line number from where the exception was thrown. |
getMessage | String | Returns the error message that displays for the user. |
getStackTraceString | String | Returns the stack trace as a string. |
getTypeName | String | Returns the type of exception, such as DmlException, ListException, MathException, and so on. |