SaasGuru Logo

Flat 20% OFF on Salesforce Marketing Cloud and Data Cloud + AI Bootcamp 🎉– Offer Ends 30th Nov!

Flat 20% OFF on Salesforce Marketing Cloud and Data Cloud + AI Bootcamp 🎉– Offer Ends 30th Nov!
Different Types of Exceptions in Salesforce

Different Types of Exceptions in Salesforce

In the vast universe of Salesforce, exceptions are akin to unexpected roadblocks that can appear on your development journey. Whether it’s a minor detour or a significant obstacle, knowing how to navigate these challenges is essential. As with all hurdles, understanding and managing them effectively not only clears the path but also enriches the journey by adding layers of knowledge and expertise.

In this comprehensive guide, you’ll unravel:

  • Understand the core concept of exceptions within the Salesforce ecosystem and understand their pivotal role in programming.
  • From the commonly encountered to the more obscure, familiarise yourself with the myriad exceptions that Salesforce might throw your way.
  • Arm yourself with actionable insights to handle exceptions like a pro, ensuring your applications run smoothly and efficiently.

Embark on this enlightening journey to transform challenges into opportunities, making your Salesforce development experience smoother and more adept. Let’s dive in!

What is Exception in Salesforce?

Within Salesforce, an “exception” denotes an unanticipated error or event that transpires while a program or process is running. Should an exception arise, it disrupts the regular progression of the program and redirects to any available error-handling method. If there is no error-handling mechanism in place, the program may terminate abruptly.

Exceptions in Salesforce can be due to various reasons, such as:

  • Trying to reference a null object.
  • Performing an illegal operation like dividing by zero.
  • Attempting to insert or update records that violate data validation rules.
  • Exceeding platform limits, such as governor limits on the number of records retrieved in a single transaction.

Types of Exceptions in Salesforce

1. DmlException

DmlException is specifically related to issues arising from Data Manipulation Language (DML) operations within Salesforce. These operations include but are not limited to insert, update, delete, and undelete actions.

Example: Imagine a scenario where you’re running a batch job to insert a list of contact records into Salesforce. If any of these records violate validation rules, say, missing a mandatory field or violating unique constraints, Salesforce will halt the process and throw a DmlException. This exception will provide detailed feedback on which record caused the issue and what specific validation was violated, aiding developers in troubleshooting.

2. ListException

This exception pertains to issues with list operations in Apex. Lists in Salesforce are akin to arrays in other programming languages and are subject to similar pitfalls.

Example: Consider an Apex class where you have a list populated with five account records. If there’s a portion of the code that tries to access an element at an index that doesn’t exist, such as the seventh element, a ListException will be thrown. The error might specify “List index out of bounds,” helping developers pinpoint the exact problem in their code.

3. NullPointerException

One of the more common exceptions across various programming languages, a NullPointerException in Salesforce, signifies that there’s an attempt to reference or use an object which hasn’t been initialised or is currently null.

Example: Suppose you have a custom Apex function that fetches a particular contact based on specific criteria. If this function returns null (because no contact matches the criteria) and you subsequently attempt to access attributes of this contact without checking for null, you’ll trigger a NullPointerException.

4. QueryException

Salesforce’s proprietary querying language, SOQL, is a powerful tool for fetching data. But like all tools, it has to be used correctly. Mistakes or oversights in SOQL queries lead to a QueryException.

Example: Imagine writing an Apex class to fetch the latest five opportunity records associated with an account. If the SOQL statement mistakenly references a field name that doesn’t exist or has a syntax error, the system will throw a QueryException detailing the nature of the faulty query.

5. LimitException

Salesforce is a multi-tenant platform, which means many organisations share the same resources. To ensure fair usage, Salesforce has governor limits. Exceeding these predefined limits results in a LimitException.

Example: In an Apex trigger designed to handle bulk record processing, if for every record you initiate a separate SOQL query, you’ll quickly hit the governor limit for the maximum number of SOQL queries in a single transaction. Once this happens, a LimitException will be thrown, alerting the developer to the inefficient code.

6. SObjectException

Salesforce revolves around standard and custom objects (often referred to as SObjects). These are the building blocks of most Salesforce data. Any mishandling or misreference of these objects leads to a SObjectException.

Example: Assume you’ve fetched a lead record but forgot to query one of its fields, say ‘Company’. Later in the code, if you attempt to access this ‘Company’ field directly without checking whether it was included in the query, Salesforce will throw a SObjectException specifying the field that was accessed without being queried.

7. System.FinalException

The System.FinalException is thrown when there is an attempt to modify a variable or class that has been declared as final. In Salesforce’s Apex language, the final keyword means that the value or definition cannot be changed once it has been set.

Example: Imagine an Apex class where a method declares a final variable and assigns it a value. If another method or operation within that class subsequently tries to alter the value of this final variable, Salesforce will throw a System.FinalException, signalling the violation of the immutability constraint.

8. StringException

StringException is associated with issues related to string operations in Apex, especially when these operations are outside the permissible bounds or entail invalid conversions.

Example: If you attempt to convert an improperly formatted string into a date, or perhaps you’re trying to access a substring using an out-of-bounds index, a StringException will be raised, informing the developer of the specific string operation that failed.

9. JSONException

As integration and data interchange become more common, handling JSON (JavaScript Object Notation) in Apex is frequent. JSONException deals with problems related to parsing or generating JSON.

Example: Consider a scenario where an external system sends a JSON payload to Salesforce. If this JSON is malformed or doesn’t adhere to expected structures (missing brackets, invalid syntax, etc.), then when trying to deserialize this JSON into an Apex object, a JSONException will be thrown, pinpointing the issue in the JSON structure.

10. UnexpectedException

This is a bit of a catch-all. UnexpectedException is thrown when Salesforce encounters an error that doesn’t fit into other predefined exception categories. It typically relates to unforeseeable issues that Salesforce wasn’t able to handle gracefully.

Example: This could arise from internal server problems, issues in multi-tenant architectures, or even certain platform bugs. The specifics of this exception are often more challenging to pin down because they’re, well, unexpected. Developers encountering this exception might need to reach out to Salesforce support for further diagnostics.

11. FlowException

Flows in Salesforce are a way to automate processes without writing code. However, they are not exempt from errors. FlowException pertains to issues arising from the execution of these automated flows.

Example: Suppose you’ve set up a flow to update a contact’s details when an associated account changes. If there’s a logic error in the flow, like trying to access a field that doesn’t exist or violating a rule, then upon the flow’s execution, Salesforce will throw a FlowException, detailing where and why the flow faltered.

Tips for Better Exception Management

Properly handling exceptions can significantly improve the user experience, reduce downtime, and simplify the debugging process. Here are some essential tips for better exception management:

1. Understand the Different Exceptions

Before you can handle exceptions, you need to understand them. Familiarise yourself with the various Salesforce exceptions, as detailed earlier, to determine the most appropriate handling techniques for each.

2. Use Try-Catch Blocks Judiciously

A try-catch block allows your code to “try” to execute a segment and “catch” any exceptions that arise. Place risky operations, like DML operations or external API calls, within a try-catch block.

try {

    // Potentially risky code

} catch (Exception e) {

    // Handle the exception

}

3. Provide Informative Error Messages

Instead of presenting users with a cryptic system-generated error message, use catch blocks to display a user-friendly error message. This can guide end-users on the next steps or help developers in troubleshooting.

4. Log Errors

Maintain a robust error logging mechanism. Store exceptions, along with their stack traces, in custom objects or external logging systems. This allows for post-incident analysis and helps in identifying recurring issues.

5. Handle Exceptions at the Right Level

Not every exception needs to be caught immediately where it occurs. Sometimes, it’s beneficial to let exceptions propagate up to higher layers of the application where they can be handled more appropriately or comprehensively.

6. Utilise Custom Exceptions

Apex allows for the creation of custom exception types by extending the base Exception class. This can be useful in defining specific behaviours for unique scenarios in your application.

public class CustomException extends Exception {}

7. Limit the Use of Generic Exceptions

While catching a generic Exception can be a catch-all, it’s not always the best practice. It can hide issues and make debugging more complex. Be as specific as possible when catching exceptions.

8. Have a Fallback Mechanism

Always have a backup plan. If an operation fails due to an exception, consider a retry mechanism or an alternate method of achieving the intended outcome.

Remember, exceptions are not inherently bad; they provide valuable feedback on what’s wrong. The goal isn’t to prevent them at all costs but to handle them gracefully when they do occur. Proper exception management ensures the resilience and reliability of your Salesforce applications

Become a Salesforce Certified Professional

Conclusion

Navigating the world of Salesforce exceptions can indeed feel like a challenging endeavor. However, with the right knowledge and tools at your disposal, it becomes a learning curve that propels you towards becoming a more seasoned developer. And while this guide offers a comprehensive look into Salesforce exceptions, remember that continuous learning and community support play an invaluable role in refining your skills further.

Want to delve deeper into the intricacies of Salesforce or simply connect with like-minded professionals? Join our saasguru community on Slack. It’s a space brimming with insights, tips, and collaborative spirits.

Whether you’re eyeing the Salesforce Admin role or aiming to be a Salesforce developer, saasguru has got you covered. Explore a range of courses tailored to your aspirations. 

Sign up with saasguru now and embark on a transformative journey in the Salesforce universe.

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

Salesforce Data Loader Errors: How to Identify and Fix Them

Learn how to identify, troubleshoot, and prevent common Salesforce Data Loader errors with actionable tips and best practices. Read now!

Humans of Salesforce – Mauricio Alexandre Silva

Discover Mauricio Alexandre Silva’s inspiring Salesforce journey, tips for success, and insights into the evolving ecosystem. Read now!

Salesforce India Achieves $1 Billion Revenue Milestone

Salesforce India achieves $1 billion revenue milestone, driven by AI, innovation, and digital transformation across industries. Read now!