Exceptions
Exceptions
Exceptions: Causes,
Implications, and Best Practices
ExceptionClass.insertContact();
In the given code, there's a list called strList containing two elements:
'Apple' and 'Banana'. The code tries to get the third element using strList[2],
but since lists start counting from 0, the index 2 refers to the third element.
However, because there are only two elements, there's nothing at index 2.
This causes an "IndexOutOfBoundsException" error because the code is
trying to access an element that doesn't exist in the list.
NullPointerException
try {
String s;
Boolean b = s.contains('abc'); // Causes a
NullPointerException
} catch(NullPointerException npe) {
System.debug('The following exception has occurred: ' +
npe.getMessage());
}
In the try block, a String variable 's' is declared but left uninitialized.
Subsequently, a call to the contains method on 's' is attempted. However,
as 's' is null, it results in a NullPointerException. This exception is caught in
the catch block, where a debug message is printed using System.debug,
conveying the occurrence of the exception.
QueryException
try {
// This statement doesn't cause an exception, even
though
// we don't have an account with name='XYZ'.
// The list will just be empty.
List<Account> accountList = [SELECT Name FROM Account
WHERE Name = 'XYZ'];
// accountList.size() is 0
System.debug(accountList.size());
Inside the try block, two SOQL queries are executed. The first query
retrieves a list of records meeting specific criteria. If no record matches the
criteria, the list will be empty, but it won't cause an exception. The second
query attempts to retrieve a single record using the LIMIT 1 clause. If no
record matches the criteria, it will cause a QueryException due to the
invalid assignment of a single record object when none are returned. In the
catch block, we handle the QueryException by printing a debug message
with the exception message using System.debug.
SObjectException
try {
// Querying for an Account record without retrieving
the Name field
Account acc = [SELECT Id FROM Account LIMIT 1];
In the provided scenario, within the try block, a query is made to retrieve an
Account record, solely selecting the Id field while excluding the Name field.
Subsequently, an attempt is made to access the Name field of the queried
Account record. Due to the omission of the Name field in the query,
accessing it triggers an SObjectException. In response, the catch block
captures this exception and executes code to handle it appropriately. In this
case, a debug message is generated using System.debug(), conveying the
occurrence of the SObjectException along with its corresponding message.
This mechanism enables developers to identify and address issues
pertaining to the retrieval and manipulation of Salesforce SObject records
comprehensively.
Mixed Dml Exception
trigger MixedDMLTrigger on Account (after insert) {
// Attempting to update a User record (setup object)
and insert a Contact record (non-setup object) in the same
transaction
User u = new User(
LastName = 'Doe',
Alias = 'JD',
Email = '[email protected]',
Username = '[email protected]',
ProfileId = [SELECT Id FROM Profile WHERE Name =
'Standard User' LIMIT 1].Id
);
insert u;
newContacts.add(duplicateContact);
}
In the provided code, we execute a loop iterating 101 times, each iteration
performing a SOQL query to retrieve one Account record. As the total
number of SOQL queries exceeds the governor limit of 100, it should
trigger the "Too Many SOQL Queries: 101" error. Upon encountering the
error, the code enters the catch block, where a debug message indicates
the occurrence of the error. This scenario accurately simulates the
condition where the code surpasses the allowed number of SOQL queries
within a single transaction, resulting in the expected error message.
Similarly, 'Too many DML statements: 151' occurs when the number of
Data Manipulation Language (DML) statements executed in a single
transaction exceeds the limit of 150 DML statements, leading to
performance issues and potential governor limit exceptions. Additionally,
'Too many query rows: 50001' indicates that a query returned more than
50,000 rows, surpassing the maximum number of rows returned by a single
query and potentially impacting application performance and stability."
Apex CPU Time Limit Exceeded
public class ExceptionClass {
public static void consumeCPUTime() {
// Perform a CPU-intensive operation
Long startTime = System.now().getTime();
while(System.now().getTime() - startTime < 10000)
{} // Loop for 10 seconds (intentionally CPU intensive)
}
}
The code defines a method named consumeCPUTime() within the
ExceptionClass class, which simulates a CPU-intensive operation by
entering a while loop that runs for 10 seconds. This loop continuously
checks the elapsed time and consumes CPU resources until the specified
duration is reached. Such CPU-intensive operations can lead to "Apex CPU
Time Limit Exceeded" errors if executed within a Salesforce transaction and
the cumulative CPU time exceeds the platform's limits, impacting various
operations like trigger execution or batch processing.
System.TypeException
public class QueryLimitExample {
public static void triggerException() {
try {
// Attempt to parse an invalid integer from a
string
Integer invalidInteger =
Integer.valueOf('abc');
} catch (System.StringException e) {
System.debug('An error occurred: ' +
e.getMessage());
}
}
}