Sei sulla pagina 1di 43

Salesforce Certified Platform Developer 1

Lesson 11: Exception Handling

©Simplilearn. All rights reserved 1


What's in It for Me

Understand exceptions and its effects

Explain exception handling

Explain Exception statements

List the different types of exception handling

©Simplilearn. All rights reserved 2


Exceptions
Understand what exceptions are and their effects

©Simplilearn. All rights reserved 3


What Are Exceptions

Exceptions are statements that are used to note down errors or any other events that disrupt the normal
execution of Apex code.

©Simplilearn. All rights reserved 4


What Happens When Exceptions Occur?

Following incidents occur when there are exceptions and they are not properly handled:

A red message is seen on the Salesforce User Interface.

This stops the execution of Apex code.

Any DML operations that were performed as a part of the transaction are rolled back.

Exceptions get logged into debug logs

Also, Apex sends out an unhandled exception email to the user who last modified
the class or trigger due to which the error has occurred.

©Simplilearn. All rights reserved 5


Exception Handling

Exception handling is the process of responding to exceptions that appear in the code during its run time.
There are many ways to contain an exception in the Apex code such as ensuring every scenario, positive or
negative, is handled.

Exception Handling

Normal Flow of Program

Exception!

Alternate way to continue


Flow of Program

Throughout this lesson, where “exception” has been used to mean errors, it has been represented in lowercase.

Where “Exception” has been used to mean built-in class, it has been represented in title case.
©Simplilearn. All rights reserved 6
Exception Statements
Understand the different keywords and statements that are used to catch
and handle exceptions in Apex

©Simplilearn. All rights reserved 7


Exception Statements and Types

There are statements that help in catching and handling exceptions in Apex code. Let’s discuss them
individually. They are:

01 throw statements and

02 Try-catch-finally statements.

©Simplilearn. All rights reserved 8


throw Statements

A throw statement is used to signal that an exception has occurred. The basic syntax of throw statement is
shown here:

throw exceptionObject;

©Simplilearn. All rights reserved 9


Try-catch-finally Statements

Try, catch, and finally are the Exception statements that can be used together to capture an exception
and handle it gracefully.

No Exception
Exception handler
handler

… Try {
…. Exceptions …
Code.. Code..
… ….
…. }

Catch block
Error!

©Simplilearn. All rights reserved 10


Try-catch-finally Statements—Syntax
try {
Let’s look at the syntax of try, catch, and finally statements.
// Try block

code_block

}
catch (exceptionType variableName) {

// Initial catch block.


A try block encloses the code where exception can occur.
// At least 1 catch block or finally block must be present.

code_block

catch (Exception e) {
Catch block is optional and comes immediately after the try
// Optional additional catch statement for other exception types. block and handles the exception.
// Note that the general exception type, 'Exception',

// must be the last catch block when it is used.

code_block

finally {

// Finally block.

// this code block is always executed


Finally block is mandatorily executed at the end.
code_block

©Simplilearn. All rights reserved 11


Demo—Exception Handling Example
Demonstrate examples of handling exceptions

©Simplilearn. All rights reserved 12


Knowledge Check

©Simplilearn. All rights reserved 13


KNOWLEDGE
CHECK
Which block of code should be used to clear out the variables in code?

a. try

b. catch

c. finally

d. A combination of try and finally

©Simplilearn. All rights reserved 14


KNOWLEDGE
CHECK
Which block of code should be used to clear out the variables in code?

a. try

b. catch

c. finally

d. A combination of try and finally

The correct answer is c

The finally block of code should be used to clear out the variables in code.

©Simplilearn. All rights reserved 15


System-Defined Exception
Discuss system-defined exceptions

©Simplilearn. All rights reserved 16


Types of System-Defined Exception

System-defined exception or built-in exceptions are Exception classes provided by Salesforce out of the box.

Types of
Exceptions

Custom or
system-defined
user-defined

NullPointer Generic
DMLException ListException QueryException
Exception Exception Type

©Simplilearn. All rights reserved 17


DMLException

DML Exceptions are exceptions that occur whenever a DML operation fails. This may happen due to many reasons, the
most common one is inserting a record without a required field.

NullPointer Generic
DMLException ListException QueryException
Exception Exception Type

try {

Position__c pos = new Position__c();

insert pos;

} catch(DmlException e) {

System.debug('The following exception has occurred: ' + e.getMessage());

©Simplilearn. All rights reserved 18


ListException

ListException catches any type of run time error with a list. This list can be of any data type such as integer, string, or
sObject.

NullPointer Generic
DMLException ListException QueryException
Exception Exception Type

try {

List<String> stringList = new List<String>();

stringList.add('John');

// This list contains only one element,

// but we're attempting to access the second element

// from this zero-based list.

String str1 = stringList[0]; //this will execute fine

String str2 = stringList[1]; // Causes a ListException

} catch(ListException le) {

System.debug('The following exception has occurred: ' + le.getMessage());

©Simplilearn. All rights reserved 19


NullPointerException

NullPointer Exception catches exceptions that occur when we try to reference a null variable. Use this exception
whenever you are referencing a variable that might turn out to be null.

NullPointer Generic
DMLException ListException QueryException
Exception Exception Type

try {

String stringVariable;

Boolean boolVariable = stringVariable.contains(‘John'); // Causes a NullPointerException

} catch(NullPointerException npe) {

System.debug('The following exception has occurred: ' + npe.getMessage());

©Simplilearn. All rights reserved 20


QueryException

QueryException catches any run time errors with SOQL queries. QueryException occurs when there is a problem in
SOQL queries such as assigning a query that returns no records or more than one record to a single sObject variable.

NullPointer Generic
DMLException ListException QueryException
Exception Exception Type

try {
// This statement doesn't cause an exception,
// if we don't have a
// The list will just be empty.
List<Position__c> positionList = [SELECT Name FROM Position__c WHERE Name='Salesforce Developer'];
// positionList.size() is 0
System.debug(positionList.size());

// However, this statement causes a QueryException because


// we're assiging the query result to a Position sObject varaible
// but no Position record is found
Position__c pos = [SELECT Name FROM Position__c WHERE Name='Salesforce Developer' LIMIT 1];
} catch(QueryException ge) {
System.debug('The following exception has occurred: ' + ge.getMessage());
}

©Simplilearn. All rights reserved 21


Generic Exception Type

This exception type can catch any type of exception; that’s why it’s called generic Exception type. This is used when you
are not sure which exception type to use and what exception might occur in the code.

NullPointer Generic
DMLException ListException QueryException
Exception Exception Type

try {
// This statement doesn't cause an exception,
// if we don't have a
// The list will just be empty.
List<Position__c> positionList = [SELECT Name FROM Position__c WHERE Name='Salesforce Developer'];
// positionList.size() is 0
System.debug(positionList.size());

// However, this statement causes a QueryException because


// we're assiging the query result to a Position sObject varaible
// but no Position record is found
Position__c pos = [SELECT Name FROM Position__c WHERE Name='Salesforce Developer' LIMIT 1];
} catch(Exception ex) {
System.debug('The following exception has occurred: ' + ex.getMessage());
}

©Simplilearn. All rights reserved 22


Exception Methods
Some exception methods

©Simplilearn. All rights reserved 23


Common Exception Methods

All Exception types are Exception classes and these classes have methods that can provide a lot of information about
the exception and error that occurred.

try { getTypeName: Returns the type of exception, such as


Position__c pos = new Position(); DmlException, ListException, and QueryException.
// Causes an QueryException because
getMessage: Returns the error message and displays for the
// we are inserting record without required fields

insert pos;
user.
} catch(Exception e) { getCause: Returns the cause of the exception as an exception
System.debug('Exception type caught: ' + e.getTypeName());
object.
System.debug('Message: ' + e.getMessage());
getLineNumber: Returns the line number from where the
System.debug('Cause: ' + e.getCause()); // returns null

System.debug('Line number: ' + e.getLineNumber()); exception was thrown.


System.debug('Stack trace: ' + e.getStackTraceString()); getStackTraceString: Returns the stack trace as a string.
}

1. 09:36:18.17 (47503607)|USER_DEBUG|[6]|DEBUG|Exception type caught: System.QueryException

2. 09:36:18.17 (47535887)|USER_DEBUG|[7]|DEBUG|Message: List has no rows for assignment to SObject

3. 09:36:18.17 (47584933)|USER_DEBUG|[8]|DEBUG|Cause: null

4. 09:36:18.17 (47630922)|USER_DEBUG|[9]|DEBUG|Line number: 2

5. 09:36:18.17 (47662729)|USER_DEBUG|[10]|DEBUG|Stack trace: AnonymousBlock: line 2, column 1


©Simplilearn. All rights reserved 24
Catching Different Exception Types
Understand how you can catch multiple types of exceptions from the
same try block

©Simplilearn. All rights reserved 25


How to Catch Different Exception Types

You can use several catch blocks—a catch block for each exception type and a final catch block that
catches the generic Exception type.

try {

Position__c pos = new Position();

// Causes an QueryException because

// we are inserting record without required fields

insert pos;

} catch(DmlException e) {

System.debug(’QueryException caught: ' + e.getMessage());

} catch(QueryException e) {

System.debug(’DMLException caught: ' + e.getMessage());

} catch(Exception e) {

System.debug('Exception caught: ' + e.getMessage());

©Simplilearn. All rights reserved 26


Custom or User-Defined Exception Handling
Look at how you can define custom or user-defined exception types

©Simplilearn. All rights reserved 27


Custom or User-Defined Exceptions
You can create your own top level Exception classes that can public class MyCustomException extends Exception {}
have their own member variables, methods, constructors,
implement interfaces, and so on.
Custom exceptions enable you to specify detailed error public class MyOtherException extends MyCustomException {}
messages and have more custom error handling in your catch
blocks.

You can construct exceptions:

With no arguments: new MyException();

With a single String argument that specifies the error message: new MyException('This is bad');

With a single Exception argument that specifies the cause and


new MyException(e);
displays in any stack trace:

With both a String error message and a chained exception


new MyException('This is bad', e);
cause that displays in any stack trace:

©Simplilearn. All rights reserved 28


Custom Defined Exception—Example
public class PositionUtility {
public static void mainProcessing() {
try {
insertPositionMethod();

Example } catch(PositionException pe) {


System.debug('Message: ' + pe.getMessage());
System.debug('Cause: ' + pe.getCause());
public class PositionException extends Exception {}
System.debug('Line number: ' + pe.getLineNumber());
System.debug('Stack trace: ' + pe.getStackTraceString());
}
}
public static void insertPositionMethod() {
try {
// Insert Position record without required fields
Position__c pos = new Position__c();
insert pos;
} catch(DmlException e) {
// Since Position record is being insert
// without required fields, DMLException occurs
throw new PositionException(
'Position record could not be inserted.', e);
}
}
}
©Simplilearn. All rights reserved 29
Quiz

©Simplilearn. All rights reserved 30


QUIZ The following custom exception class has been defined public class MyCustomException extends

1 Exception { } Which statement would you use to throw the exception? Select any two.

a. throw MyCustomException();

b. try catch throw MyCustomException();

c. throw new MyCustomException('Problem found');

d. throw new MyCustomException();

©Simplilearn. All rights reserved 31


QUIZ The following custom exception class has been defined public class MyCustomException extends

1 Exception { } Which statement would you use to throw the exception? Select any two.

a. throw MyCustomException();

b. try catch throw MyCustomException();

c. throw new MyCustomException('Problem found');

d. throw new MyCustomException();

The correct answer is c and d.

Use throw new MyCustomException('Problem found'); and throw new MyCustomException(); to throw the
exception.

©Simplilearn. All rights reserved 32


QUIZ A list of string called "stringList“ has 2 items added to it. Which of these statements will result in an

2 exception? Select any two.

a. stringList[0]

b. stringList[1]

c. stringList[2]

d. stringList[3]

©Simplilearn. All rights reserved 33


QUIZ A list of string called "stringList“ has 2 items added to it. Which of these statements will result in an

2 exception? Select any two.

a. stringList[0]

b. stringList[1]

c. stringList[2]

d. stringList[3]

The correct answer is c and d.

Since there are only two items in the list, here you are trying to access the item at 3rd index; this will throw
an error.

©Simplilearn. All rights reserved 34


QUIZ
Which of these statements will NOT throw an exception if there are no records in the Salesforce org?
3

a. List<Position__c> posList = [select id from Position__c limit 1];

b. Position__c posList = [select id from Position__c limit 1];

c. Position__c posList = [select id from Position__c];

d. String query = 'select id from Position__c';Position__c posList =


Database.query(query);

©Simplilearn. All rights reserved 35


QUIZ
Which of these statements will NOT throw an exception if there are no records in the Salesforce org?
3

a. List<Position__c> posList = [select id from Position__c limit 1];

b. Position__c posList = [select id from Position__c limit 1];

c. Position__c posList = [select id from Position__c];

d. String query = 'select id from Position__c';Position__c posList =


Database.query(query);

The correct answer is c.

Since we are fetching records in a list, List<Position__c> posList = [select id from Position__c limit 1];
will not throw an exception.

©Simplilearn. All rights reserved 36


QUIZ
Why do we declare and define custom exception classes?
4

a. They are easy to use

b. The messages are easy to read

c. They are the only way to catch errors in apex code

d. Custom exceptions enable you to specify detailed error messages

©Simplilearn. All rights reserved 37


QUIZ
Why do we declare and define custom exception classes?
4

a. They are easy to use

b. The messages are easy to read

c. They are the only way to catch errors in apex code

d. Custom exceptions enable you to specify detailed error messages

The correct answer is d.

We declare and define custom exception classes because custom exceptions enable you to specify detailed
error messages.

©Simplilearn. All rights reserved 38


QUIZ If multiple catch blocks are used in a code, then is it necessary for all of them to be executed for an

5 exception to be caught?

a. Yes

b. No

©Simplilearn. All rights reserved 39


QUIZ If multiple catch blocks are used in a code, then is it necessary for all of them to be executed for an

5 exception to be caught?

a. Yes

b. No

The correct answer is b.

If a catch block on the 1st or 2nd level is relevant to the exception thrown, then other catch blocks below it
are not executed.

©Simplilearn. All rights reserved 40


Key Takeaways

©Simplilearn. All rights reserved 41


Key Takeaways

• Exceptions help us in handling run time errors in code.


• Try, catch, and finally are Exception statements that can be used together to capture an exception and
handle it gracefully.
• There are different types of Exceptions such as DMLException, List Exception, and QueryException.
• Exception methods help in getting more information on an error.
• You can define your own custom exceptions by creating custom Exception class.

©Simplilearn. All rights reserved 42


This concludes “Exception Handling.”
The next lesson is “Debugging.”

©Simplilearn. All rights reserved 43

Potrebbero piacerti anche