Unexpected errors happen in code; that’s where exception handling comes in. This blog will introduce you to the tools Apex provides to manage errors gracefully, ensuring your code continues to run smoothly.
By reading this blog, you’ll learn:
- The fundamentals of exceptions: What they are and how ‘throw’ statements work.
- How to control errors: Using ‘try’, ‘catch’, and ‘finally’ statements.
- Key exception methods: Understanding methods like getMessage and getStackTraceString.
- Practical examples: See how exception handling works in real-world Salesforce scenarios.
Exception Handling in Apex
An exception is an unexpected event that disrupts the normal flow of the Apex code. Throw statements are used to generate exceptions, while try, catch, and finally, statements are used to recover from exceptions.
Exception Statements
Throw statement enables the developer to throw the exception along with the exception object, which contains the details of the exception. Exception object can be further utilized to handle the exception more efficiently by using:
- try statement is used to enclose the block of code in which the exception might occur.
- catch statement in apex is used to handle a particular type of exception. 1 try statement can have multiple catch statements associated with it but with different exception types. Only 1 catch block is executed during an exception.
- finally statement is a piece of code that is executed regardless of the exception was thrown or not. Only 1 Finally statement can be associated with to try-catch block. Finally can be used to clean up code, like freeing up resources.
try 1
// 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 }
Also Read – Different Types of Exceptions in Salesforce
Exception Methods
Methods | Return type | Explanation |
getCause | Exception | Returns the cause of exception as exception object. |
getLineNumber | Integer | Returns the line number where the exception occurred |
getMessage | String | Returns the error message displayed to the user. |
getStackTraceString | String | Returns Stack trace as a string. |
getTypeName | String | Returns the type of exception like NullPointerException, DMLEXception, LimitException, ListException, etc. |
Example of Handling Exception
(//DML Exception Example
CustomObject_c co=new CustomObject_c();
insert co;|)
Insert the DML statement in the above code will cause DMLException since the required fields for CustomObject_c during insertion have not been assigned values. The below-given error will be displayed in the debug log once the code executes.
System.DmlException: Insert failed. First exception on row 0; first error:
REQUIRED_FIELD_MISSING, Required fields are missing: [Description, Price, Total
Inventory]: [Description, Price, Total Inventory]
Next, we can try to execute the below-given code snippet, which works similar to the above code but it includes a try-catch block.
(//Handling DML Exception
try {
Customobject.
_c m = new CustomObject_c();
insert m;
// This doesn’t execute since insert causes an exception
System.debug( ‘Statement after insert.’);
}
catch(DmlException e) {
System.debug( ‘The following exception has occurred: ‘ + e-getMessage());
}
)
The above code will now run successfully in the developer console since we are handling the exception in the catch block and display the message in the debug log which caused the exception. Also, statements after exception are not executed. In this case, line number 6 will not be executed.
To execute lines of code after exception, we can include the finally statement. Finally statement will execute the code regardless of the exception that occurred.
(
//Handling DML Exception
try f
CustomObject
c m = new CustomObject_c();
insert m;
} catch(DmlException e) {
System.debug(‘The following exception has occurred: ‘ + e-getMessage());
finally(
// This doesn’t execute since insert causes an exception
System.debug(‘Statement after insert.’);
}
)
Conclusion
You’ve learned the essentials of Apex exception handling and understand how try-catch-finally structures can safeguard your code. With these tools and techniques in hand, you’re now better prepared to tackle errors head-on.
Ready to enhance your skills even further? Join saasguru for a free trial and gain access to 24+ Salesforce certification courses, 50+ mock exams, and 50+ Salesforce labs. Take charge of your Salesforce journey and build error-resilient applications confidently!