Newer Version Available
Exception Statements
Apex uses exceptions to note errors and other events that disrupt the normal flow of code execution. throw statements can be used to generate exceptions, while try, catch, and finally can be used to gracefully recover from an exception.
Throw Statements
Try-Catch-Finally Statements
- The try statement identifies a block of code in which an exception can occur.
- The catch statement identifies a block of code that can handle a particular type of exception. A single try statement can have zero or more associated catch statements. Each catch statement must have a unique exception type. Also, once a particular exception type is caught in one catch block, the remaining catch blocks, if any, aren’t executed.
- The finally statement identifies a block of code that is guaranteed to execute and allows you to clean up your code. A single try statement can have up to one associated finally statement. Code in the finally block always executes regardless of whether an exception was thrown or the type of exception that was thrown. Because the finally block always executes, use it for cleanup code, such as for freeing up resources.
Syntax
The syntax of the try, catch, and finally statements is as follows.
At least a catch block or a finally block must be present with a try block. The following is the syntax of a try-catch block.
The following is the syntax of a try-finally block.
Exceptions that Can’t be Caught
Some special types of built-in exceptions can’t be caught. Those exceptions are associated with critical situations in the Lightning Platform. These situations require the abortion of code execution and don’t allow for execution to resume through exception handling. One such exception is the limit exception (System.LimitException) that the runtime throws if a governor limit has been exceeded, such as when the maximum number of SOQL queries issued has been exceeded. Other examples are exceptions thrown when assertion statements fail (through System.assert methods) or license exceptions.
When exceptions are uncatchable, catch blocks, as well as finally blocks if any, aren’t executed.