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 exceptionObject;
The syntax of the try, catch, and finally statements is as follows.
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 with a try block. The following is the syntax of a try-catch block.
try { code_block } catch (exceptionType variableName) { code_block } // Optional additional catch blocks
The following is the syntax of a try-finally block.
try { code_block } finally { code_block }
try { // Perform some operation that // might cause an exception. } catch(Exception e) { // Generic exception handling code here. } finally { // Perform some clean up. }
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.
Boolean x = true; throw new NullPointerException(); x = false;