Earn a Salesforce AI Certification by IIT + 12-Week Internship Secure Your Spot Today!

Earn a Salesforce AI Certification by IIT + 12-Week Internship Secure Your Spot Today!
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

Unlock Your AI -Powered Assistant

Gain Exclusive Access to Your Salesforce Copilot

Related Articles

Mass Assign User Permission Set in Salesforce

Learn how to efficiently mass assign user permission sets in Salesforce using tools like Data Loader. Save time and ensure accuracy. Read now!

How to Clone a FlexCard in Salesforce

Learn how to clone a FlexCard in Salesforce with this step-by-step guide. Simplify customization and boost efficiency effortlessly!

Salesforce Introduces Agentforce 2.0: Redefining How Work Gets Done

Salesforce introduces Agentforce 2.0, the AI platform transforming digital labor with autonomous agents and seamless workflows. Read now!