DML Exceptions
Debug log will be: The following exception has occurred: SObject row was retrieved via SOQL without querying the requested field: Merchandise__c.Total_Inventory__c
Any problem with a DML statement, such as an insert statement missing a required field on a record.
ListException
Any problem with a list, such as attempting to access an index that is out of bounds.
- try
- {
- List<Integer> li = new List<Integer>();
- li.add(15);
- // This list contains only one element, but we're attempting to access the second element from this zero-based list.
- Integer i1 = li[0];
- Integer i2 = li[1]; // Causes a ListException
- }
- catch(ListException le)
- {
- System.debug('The following exception has occurred: ' + le.getMessage());
- }
Debug log will be: The following exception has occurred: List index out of bounds: 1 .
NullPointerException
Any problem with dereferencing a null variable.
Try out some code that does some things on purpose to cause this exception to be thrown. Execute the following:
- try
- {
- String s;
- Boolean b = s.contains('abc'); // Causes a NullPointerException
- }
- catch(NullPointerException npe)
- {
- System.debug('The following exception has occurred: ' + npe.getMessage());
- }
Debug will be: The following exception has occurred: Attempt to de-reference a null object
QueryException
Any problem with SOQL queries, such as assigning a query that returns no records or more than one record to a singleton sObject variable.
- try
- {
- // This statement doesn't cause an exception, even though we don't have a merchandise with name='XYZ'.
- // The list will just be empty.
- List<Merchandise__c> lm = [SELECT Name FROM Merchandise__c WHERE Name='XYZ'];
- // lm.size() is 0
- System.debug(lm.size());
- // However, this statement causes a QueryException because we're assiging the return value to a Merchandise__c object but no Merchandise is returned.
- Merchandise__c m = [SELECT Name FROM Merchandise__c WHERE Name='XYZ' LIMIT 1];
- }
- catch(QueryException qe)
- {
- System.debug('The following exception has occurred: ' + qe.getMessage());
- }
Debug log will be The following exception has occurred: List has no rows for assignment to SObject .
SObjectException
Any problem with sObject records, such as attempting to change a field in an update statement that can only be changed during insert .
Try out some code that does some things on purpose to cause this exception to be thrown. Execute the following:
- try
- {
- Merchandise__c m = [SELECT Name FROM Merchandise__c LIMIT 1]; // Here No use of Limit.
- // Causes an SObjectException because we didn't retrieve the Total_Inventory__c field.
- Double inventory = m.Total_Inventory__c;
- }
- catch(SObjectException se)
- {
- System.debug('The following exception has occurred: ' + se.getMessage());
- }
Debug log will be: The following exception has occurred: SObject row was retrieved via SOQL without querying the requested field: Merchandise__c.Total_Inventory__c
No comments:
Post a Comment