0% found this document useful (0 votes)
14 views7 pages

Expection Handling

Uploaded by

joharsai369
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views7 pages

Expection Handling

Uploaded by

joharsai369
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Exception handling

Exception handling refers to the mechanism that allows developers to manage and
respond to runtime errors in their code gracefully. Proper exception handling is crucial
for building robust applications that can handle unexpected situations without crashing
or causing data corruption.

Key Concepts in Exception Handling:

Exception:

An exception is an event that occurs during the execution of a program that


disrupts the normal flow of the application.

Try-Catch Block:

This is the main mechanism used to handle exceptions in Apex (Salesforce’s


programming language). It allows you to "try" to execute a piece of code and
"catch" any errors or exceptions that occur.

Throw Statement:

If an exception occurs, the throw statement can be used to pass the exception
to a higher level in the call stack, or to generate a custom exception.

Finally Block:

This block is optional but is used to execute code regardless of whether an


exception was thrown or not (like cleanup actions).

N.Veera Raghavamma
Types of Exceptions:

● Built-in Exceptions: Salesforce provides many predefined exception types,


such as:
○ DmlException: For errors related to DML operations (insert, update,
delete).
○ QueryException: For errors related to SOQL queries.
○ NullPointerException: For attempts to dereference a null object.
○ ListException, MathException, SearchException, etc.

● Custom Exceptions: You can define your own exception classes by extending
the Exception class to handle specific business logic issues.

Example of Try-Catch-Finally Block:

try {

Account acc = new Account(Name = 'Test Account');

insert acc;

} catch (DmlException e) {

System.debug('An error occurred: ' + e.getMessage());

} catch (Exception e) {

System.debug('An unexpected error occurred: ' +


e.getMessage());

} finally {

N.Veera Raghavamma
System.debug('This will always run, even if an exception is
thrown.');

Key Components of Exception Handling:

1. Try Block:

This block contains the code that may throw an exception. Salesforce executes the
code in the try block and looks for any exceptions.

try

List<Account> accounts =[SELECT Id FROM Account WHERE Name =


'Test'];

2. Catch Block:

If an exception is thrown, the catch block catches and handles it. You can have multiple
catch blocks for different types of exceptions.

catch (DmlException e)

System.debug('Error: ' + e.getMessage());

N.Veera Raghavamma
catch (QueryException e)

System.debug('SOQL Error: ' + e.getMessage());

3. Finally Block:

The finally block contains code that will always execute, regardless of whether an
exception occurred or not. It’s often used for cleanup actions like closing resources or
logging.

finally

System.debug('This will always be executed.');

Custom Exceptions

You can create custom exceptions in Salesforce to represent specific business logic
errors.

public class CustomBusinessException extends Exception {}

public class AccountService {

public void createAccount(String accountName) {

if (accountName == null) {

N.Veera Raghavamma
throw new CustomBusinessException('Account name
cannot be null');

Account acc = new Account(Name = accountName);

insert acc;

Best Practices for Exception Handling:

Handle Specific Exceptions:

Always catch specific exceptions (e.g., DmlException, QueryException) before


catching generic ones (Exception). This helps in identifying the exact cause of the
error.

Avoid Empty Catch Blocks:

Do not leave catch blocks empty. Always log or take corrective action. For example:

catch (DmlException e) {

System.debug('DML failed: ' + e.getMessage());

Use Finally Block for Cleanup:

If there are resources that need to be released or actions that must be taken regardless
of success or failure, put them in the finally block.

N.Veera Raghavamma
Logging and Debugging:

Always log exceptions with useful information (like stack traces or error messages) to
help diagnose the issue. Use System.debug() or platform logging features.

Rethrow Exceptions When Necessary:

Sometimes you might want to handle an exception and then rethrow it to be handled at
a higher level.

catch (Exception e)

System.debug('Error: ' + e.getMessage());

throw e;

Limit Try-Catch Block Scope:

Only wrap the code that is prone to errors in a try-catch block. Wrapping large chunks of
code can make it harder to pinpoint issues.

N.Veera Raghavamma
Example of Complex Exception Handling:

public void processAccounts() {


try {

Account acc = new Account(Name = 'Test Account');


insert acc;
updateAccounts();
} catch (DmlException e) {
System.debug('DML Exception: ' + e.getMessage());
throw e;
} catch (CustomBusinessException e) {
System.debug('Custom Exception: ' + e.getMessage());
} catch (Exception e) {
System.debug('Unknown Exception: ' + e.getMessage());
} finally {
System.debug('Process completed, cleaning up.');
}
}

N.Veera Raghavamma

You might also like