Wednesday 29 August 2012

What Is an Exception? - Apex

Exceptions note errors and other events that disrupt the normal flow of code execution. throw statements are used to generate exceptions, while trycatch, andfinally 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 organization ID and user ID of the running user, as well as the exception message.
If you run 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:

Unhandled exception in the New Merchandise page 

No comments:

Post a Comment