Newer Version Available
Catching Different Exception Types
In the previous examples, we used the specific exception type in the catch block. We could have also just caught the generic Exception type in all examples, which catches all exception types. For example, try running this example that throws an SObjectException and has a catch statement with an argument type of Exception. The SObjectException gets caught in the catch block.
1try {
2 Merchandise__c m = [SELECT Name FROM Merchandise__c LIMIT 1];
3 // Causes an SObjectException because we didn't retrieve
4 // the Total_Inventory__c field.
5 Double inventory = m.Total_Inventory__c;
6} catch(Exception e) {
7 System.debug('The following exception has occurred: ' + e.getMessage());
8}Alternatively, you can have several catch blocks—a catch block for each exception type, and a final catch block that catches the generic Exception type. Look at this example. Notice that it has three catch blocks.
1try {
2 Merchandise__c m = [SELECT Name FROM Merchandise__c LIMIT 1];
3 // Causes an SObjectException because we didn't retrieve
4 // the Total_Inventory__c field.
5 Double inventory = m.Total_Inventory__c;
6} catch(DmlException e) {
7 System.debug('DmlException caught: ' + e.getMessage());
8} catch(SObjectException e) {
9 System.debug('SObjectException caught: ' + e.getMessage());
10} catch(Exception e) {
11 System.debug('Exception caught: ' + e.getMessage());
12}- The first catch block argument is of type DmlException, which doesn’t match the thrown exception (SObjectException.)
- The second catch block argument is of type SObjectException, which matches our exception, so this block gets executed and the following message is written to the debug log: SObjectException caught: SObject row was retrieved via SOQL without querying the requested field: Merchandise__c.Total_Inventory__c.
- The last catch block is ignored since one catch block has already executed.
The last catch block is handy because it catches any exception type, and so catches any exception that was not caught in the previous catch blocks. Suppose we modified the code above to cause a NullPointerException to be thrown, this exception gets caught in the last catch block. Execute this modified example. You’ll see the following debug message: Exception caught: Attempt to de-reference a null object.
1try {
2 String s;
3 Boolean b = s.contains('abc'); // Causes a NullPointerException
4} catch(DmlException e) {
5 System.debug('DmlException caught: ' + e.getMessage());
6} catch(SObjectException e) {
7 System.debug('SObjectException caught: ' + e.getMessage());
8} catch(Exception e) {
9 System.debug('Exception caught: ' + e.getMessage());
10}