Newer Version Available
Exceptions in Apex
Exceptions note errors and other events that disrupt the normal flow of code execution. throw statements are used to generate exceptions, while try, catch, and finally statements are used to gracefully recover from exceptions.
There are many ways to handle errors in your code, including using assertions like System.assert calls, or returning error codes or Boolean values, so why use exceptions? The advantage of using exceptions is that they simplify error handling. Exceptions bubble up from the called method to the caller, as many levels as necessary, until a catch statement is found that will handle the error. This relieves you from writing error handling code in each of your methods. Also, by using finally statements, you have one place to recover from exceptions, like resetting variables and deleting data.
What Happens When an Exception Occurs?
When an exception occurs, code execution halts and any DML operations that were processed prior to the exception are rolled back and aren’t committed to the database. Exceptions get logged in debug logs. For unhandled exceptions, that is, exceptions that the code doesn’t catch, Salesforce sends an email to the developer with the exception information and the end user sees an error message in the Salesforce user interface.
Unhandled Exception Emails
The developer specified in the LastModifiedBy field receives the error via email with the Apex stack trace and the customer’s organization and user ID. No other customer data is returned with the report.
Unhandled Exceptions in the User Interface
If an end user runs into an exception that occurred in Apex code while using the standard user interface, an error message appears on the page showing you the text of the unhandled exception as shown below: