Free Salesforce Developers Tutorials >

Chapter 10 - Exception Handling >

Custom or User-Defined Exceptions

Custom or User-Defined Exceptions

What You’ll Learn


S2 Labs

What Is Custom Exceptions In Apex?

You can create your own top level Exception classes that can have their own member variables, methods, constructors, implement interfaces, and so on.

Example:

 public class MyCustomException extends Exception {}
  • Custom exceptions enable you to specify detailed error messages and have more custom error handling in your catch blocks.

Example:

public class MyOtherException extends MyCustomException {}
  • You can construct exceptions
  • With no arguments

Example:

 new MyException();
  • With a single String argument that specifies the error message:

Example:

 new MyException('This is bad');
  • With a single Exception argument that specifies the cause and displays in any stack trace:

Example:

new MyException(e);
  • With both a String error message and a chained exception cause that displays in any stack trace:

Example:

 new MyException('This is bad', e);

Example:

 public class PositionException extends Exception {}
                    public class PositionUtility {
                        public static void mainProcessing() {
                            try {
                                insertPositionMethod();
                            } catch (PositionException pe) {
                                System.debug('Message: ' + pe.getMessage());
                                System.debug('Cause: ' + pe.getCause());
                                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);
                            }
                        }
                    }

salesforce-developer

  • When an exception occurs, code execution halts. 
  • Any DML operations that were processed before the exception are rolled back and aren’t committed to the database. 
  • Exceptions get logged in debug logs. 
  • For unhandled exceptions, that is, exceptions that the code doesn’t catch, Salesforce sends an email that includes the exception information. 
  • The end user sees an error message in the Salesforce user interface.

Exception Statements

There are different types of exception statements in apex:

1. Throw Statements

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

throw exceptionObject;

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

Try: A try block encloses the code where exception can occur.

Catch: Catch block is optional and comes immediately after the try block and can handle a particular type of exception. A single try statement can have zero or more associated catch statements where each catch statement must have a unique exception type. 

Note:

Once a particular exception type is caught in one catch block, the remaining catch blocks (if any) are not executed.

Finally: Finally block is mandatorily executed at the end whether the exception occured in the try block or not.

It is not compulsory for every try block to have finally associated with it and also there can be at max only 1 finally block that can be associated to 1 try block.

Finally block is generally used to cleanup code or for freeing up resources.

Note:

With every try block there should be at least 1 catch or 1 finally block associated.

Let’s look at the syntax of try, catch, and finally statements:

 try{
    // Try block 
}
catch (exceptionType variableName) {
    // Initial catch block. 
    // At least 1 catch block or finally block must be present. 
} catch (Exception e) {
    // Optional additional catch statement for other exception types. 
    // Note that the general exception type, 'Exception' must be the last catch block when it is used. 
} finally {
    // Finally block. 
    // this code block is always executed 
}

Exceptions That Can’t be Caught

There are some special types of built-in exceptions that can’t be caught. Those exceptions are associated with critical situations in the Lightning Platform. These situations require the abortion of code execution and don’t allow for execution to resume through exception handling. 

Example:

One such exception is the limit exception (System.LimitException) that the runtime throws if a governor limit has been exceeded, such as when the maximum number of SOQL queries issued has been exceeded. 

Other examples are exceptions thrown when assertion statements fail (through System.assert methods) or license exceptions.

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 *