Apex Exception Handling

by | Nov 24, 2022 | Salesforce

Home » Salesforce » Apex Exception Handling

Introduction

Exception handling is needed in the program to run the code smoothly without any breakage or disruption.

What is an Exception in Apex?

Apex uses exceptions(unexpected events) to note errors and other events that disrupt or break the normal flow of code execution.

It is an error thrown by Apex when something bad happens in the code which the program can’t handle during execution. In other words, once a program or code throws an exception, the complete transaction is rolled back, including DML transactions as well.

What causes Exceptions?

There are multiple causes of exceptions, but the most common could be when we are performing some DML operation or null object or when we are doing a callout.

What does Exception Handling mean?

When we encounter any exception during the execution of our code, with the help of ‘Try’, ‘Catch’, ‘Finally’, we can handle exceptions gracefully.

How Does Exception Handling Work?

The try, catch, and finally, blocks are used to recover from an exception.

Try: Try block identifies a code in which there are possibilities of an exception to occur.

Catch: It is used to handle a particular type of exception. One try block can have multiple catch blocks with different types of exceptions in each catch block. But if an exception is caught by one catch block, then the remaining catch blocks won’t get executed.

Finally: Finally block always gets executed regardless of whether an exception was thrown.

We can have multiple catch blocks for a single try block but only one final block per try block. It is also used to clean up the code.

Syntax of Try, Catch, and Finally

try{
//try block code
}catch(DmlException e){
//DmlException handling code
}catch(Exception e){
//Generic exception handling code
//It should be the last catch block
}finally{
//finally block to do some clean-up
}

 

Example:

Account acc = new Account(Name='Account Creation');
try{
insert acc; //DML statement
}catch(DmlException e){
System.debug('Exception has occurred - ' + e.getMessage());
}

 

Exceptions that can’t be caught

There are some exceptions that can’t be caught using try, catch or finally block; one of them is LimitException. It occurs when a governor limit is exceeded, such as when a maximum number of SOQL or DML has been exceeded.

 

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author