What’s an Exception
An exception is an unexpected event that occurs when code is executing. Basically apex is signalling there is a problem and that it can’t deal with the issue.
Salesforce has about twenty different exceptions that can be thrown when there is a problem.
What Causes Exceptions
In a lot of cases within Salesforce, the error is most likely related to doing a callout, a null object, or when doing some sort of dml operation. Most exceptions are preventable by having a good, reliable, and repeatable programming process.
The most common exceptions are usually these exceptions:
- DmlException are usually the result of a required field not being set, a record that’s been deleted, etc. I find this error is usually caused by a new validation rule being created or when I’m creating test data.
- QueryException is usually the result of getting back a list instead of a single item. Usually this means the query is returning more than one result.
- NullPointerException usually caused by not initializing a variable and then trying to do some sort of operation on it.
How Exception Handling Works
Apex implements the relatively standard try, catch and finally blocks that most C++ variants have implemented. As Apex is based off of Java, it works in basically the exact same way.
try { doSomething(); } catch (Exception ex) { system.debug('Uh oh an error occurred!'); }
Apex also supports the finally block which is always called regardless of whether an exception has occurred. Finally is usually used to do some cleanup of resources.
try { doSomething(); } catch (Exception ex) { system.debug('Uh oh an error occurred!'); } finally { doSomeCleanup(); }
Best Practices for Exception Handling in Apex
- Never just catch Exception, instead catch the specific type of exceptions. For example, QueryException should be caught if you know it’s possible you might not have any records in the query. I commonly use a pattern like this for finding if there’s any associated tasks:
try { tskId = [select Id from Task Where AccountId =: accId]; } catch (QueryException ex) { tskId = null }