fbpx

Free Salesforce Developers Tutorials >

Chapter 10 - Exception Handling >

System-Defined Exceptions and Types

System-Defined Exceptions and Types

What You’ll Learn


S2 Labs

What Is System Defined Exception?

System Defined Exceptions are the exceptions that are already defined in Salesforce, so, whenever any logical issue comes up while executing the code, the system immediately throws such an exception.

Types of System-Defined Exceptions

1. DML Exception

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.

Ex:

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

2. 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.

Ex:

try {
    List < String > stringList = new List < String > ();
    stringList.add('Bhavna');
    // This list contains only one element, 
    // but we will attempt 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());
}

3. 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.

Ex:

try {
        String stringVariable;
        Boolean boolVariable = stringVariable.contains(‘John '); 
            // Causes a NullPointerException 
        }
        catch (NullPointerException npe) {
            System.debug('The following exception has occurred: ' + npe.getMessage());
        }

salesforce-developer

4. 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.

Example:

try {
            // This statement doesn't cause an exception, 
            // if we don't have a problem in SOQL Queries. 
            // 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());
        }

5. Generic Exception

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

Example:

try {
            List < Position__c > positionList = [SELECT Name FROM Position__c WHERE Name = 'Salesforce Developer'];
            // positionList.size() is 0 
            System.debug(positionList.size());
            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());
        }

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.

  1. getTypeName(): Returns the type of exception, such as DmlException, ListException, and QueryException. 
  2. getMessage(): Returns the error message and displays it for the user.
  3. getCause(): Returns the cause of the exception as an exception object.
  4. getLineNumber(): Returns the line number from where the exception was thrown.
  5. getStackTraceString(): Returns the stack trace as a string. 

Example:

 try {
            Position__c pos = new Position();
            // Causes an QueryException because 
            // we are inserting record without required fields 
            insert pos;
        }
        catch (Exception e) {
            System.debug('Exception type caught: ' + e.getTypeName());
            System.debug('Message: ' + e.getMessage());
            System.debug('Cause: ' + e.getCause()); // returns null 
            System.debug('Line number: ' + e.getLineNumber());
        }
        USER_DEBUG | [6] | DEBUG | Exception type caught: System.QueryException USER_DEBUG | [7] | DEBUG | Message: List has no rows
        for assignment to SObject USER_DEBUG | [8] | DEBUG | Cause: null
        USER_DEBUG | [9] | DEBUG | Line number: 2
        USER_DEBUG | [10] | DEBUG | Stack trace: AnonymousBlock: line 2, column 1

Salesforce Admin Training

Download Study Material

Get access to exclusive study material for Salesforce Certification and ace your exams!

Download Now

Our Salesforce Certification Courses

Hey there! Glad you made it through our Salesforce Developer Training for beginners . But wait! We've got some high-in-demand Salesforce courses for you to take your Salesforce skills to the next level, making you a desired professional in the Salesforce job market.

Post a Comment

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