Newer Version Available

This content describes an older version of this product. View Latest

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

A throw statement allows you to signal that an error has occurred. To throw an exception, use the throw statement and provide it with an exception object to provide information about the specific error. For example:
1throw exceptionObject;

Try-Catch-Finally Statements

The try, catch, and finally statements can be used to gracefully recover from a thrown exception:
  • 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 multiple associated catch statements; however, 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 optionally identifies a block of code that is guaranteed to execute and allows you to clean up after the code enclosed in the try block. A single try statement can have only one associated finally statement. Code in the finally block always executes regardless of the type of exception that was thrown and handled.

Syntax

The syntax of these statements is as follows:

1try {
2 code_block
3} catch (exceptionType) {
4 code_block
5}
6// Optional catch statements for other exception types.
7// Note that the general exception type, 'Exception',
8// must be the last catch block when it is used.
9} catch (Exception e) {
10 code_block
11}
12// Optional finally statement
13} finally {
14 code_block
15
16}
This is a skeletal example of a try-catch-finally block.
1swfobject.registerObject("clippy.codeblock-2", "9");try {
2    // Perform some operation that 
3    //   might cause an exception.
4} catch(Exception e) {
5    // Generic exception handling code here.
6} finally {
7    // Perform some clean up.
8}

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 Force.com 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.