SaasGuru Logo

🎉Elevate your Salesforce career with our exclusive Data Cloud + Einstein Copilot Bootcamp. Join the Waitlist 🎉

🎉Elevate your Salesforce career with our exclusive Data Cloud + Einstein Copilot Bootcamp. Join the Waitlist 🎉
Exception Handling in Apex in Salesforce

Exception Handling in Apex in Salesforce 

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.

saasguru salesforce labs

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 ExceptionReturns the cause of exception as exception object.
getLineNumberIntegerReturns the line number where the exception occurred
getMessage String Returns the error message displayed to the user.
getStackTraceString StringReturns Stack trace as a string.
getTypeNameStringReturns 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!

Table of Contents

Subscribe & Get Closer to Your Salesforce Dream Career!

Get tips from accomplished Salesforce professionals delivered directly to your inbox.

Looking for Career Upgrade?

Book a free counselling session with our Course Advisor.

By providing your contact details, you agree to our Terms of use & Privacy Policy

Unsure of Your Next Step?

Take our quick 60-second assessment to discover the Salesforce career path or learning journey that’s a perfect fit for you.

Related Articles

Salesforce Service Cloud Implementation Guide 2024

Streamline your customer service with Salesforce Service Cloud implementation. Learn best practices and common challenges and elevate your support operations.

Salesforce’s New AI-Powered MuleSoft Integrations Transform B2B and B2C

Discover Salesforce’s new AI-driven MuleSoft solutions for streamlined B2B/B2C integration and enhanced order lifecycle management. Read now!

How To Import CRM Data to Data Cloud Using Data Stream?

Learn how to import data from Salesforce CRM to Data Cloud Home Org using Data Streams for seamless integration of Contact, Case, and custom objects.