SIGN IN SIGN UP

Login to your account

Username or Email *
Password *
Remember Me
Apex Intermediate Progress | ( Lessons)

Lesson: 03 Exception Handling


try {
    Account ac = new Account();
    insert ac;
} catch(DmlException e) {
    System.debug('The following exception has occurred: ' + e.getMessage());
}

Notice that the request status in the Developer Console now reports success. This is because the code handles the exception.

try {
    Account ac = new Account();
    insert ac;
    // This doesn't execute since insert causes an exception
    System.debug('Statement after insert.');
} catch(DmlException e) {
    System.debug('The following exception has occurred: ' + e.getMessage());
}

In the new debug log entry, notice that you don’t see a debug message of Statement after insert. This is because this debug statement occurs after the exception caused by the insertion and never gets executed.

try {
    Account ac = new Account();
    insert ac;
} catch(DmlException e) {
    System.debug('The following exception has occurred: ' + e.getMessage());
}
// This will get executed
System.debug('Statement after insert.');

Alternatively, you can include additional try-catch blocks.

try {
    Account ac = new Account();
    insert ac;
} catch(DmlException e) {
    System.debug('The following exception has occurred: ' + e.getMessage());
}

try {
    System.debug('Statement after insert.');
    // Insert other records
}
catch (Exception e) {
    // Handle this exception here
}

The finally block always executes regardless of what exception is thrown, and even if no exception is thrown. Let’s see it used in action. Execute the following

 


Prev You need to login to have access to the quizzes. Next

Mastered by 70 users.

Apex Intermediate

A. Apex DML Operations (8 lessons)
B. Apex Classes (17 lessons)
C. Apex Triggers (9 lessons)
D. Apex Exceptions (11 lessons)
E. Asynchronous Apex (6 lessons)
F. SOSL (10 lessons)
G. Testing Apex (9 lessons)
H. Apex Fast Recap (142 lessons)
I. Build Apex Coding Skills (64 lessons)

You need to complete all the quizzes before certification.

Go to top