Back to Top

How to create custom exception class in APEX

Updated 31 July 2017

Now and then every developer might have had faced the need to use an exception class which is not normally provided by the platform they are working on. Luckily, these days every platform provides inheritance features and hence we have the power to inherit the standard exception class of every platform. Same is the case with APEX which has a standard exception class that we can extend to create our own exceptions. This is what I am going to demonstrate, how to create custom exception class in APEX.

Exception Class

The exception class is easy to extend and does not have any abstract methods, hence you do not actually need to create any method in the extended class. However it is always a good practice to override at least the getMessage() function, so that when you use those classes, you’ll have an idea about why the exception is occurring.

Exception Class gives these following methods to use, by overriding them:

  • getLineNumber() – Returns the line number of the origination of exception.
  • getStackTraceString() – Returns the trace string of the origination of exception.
  • getTypeName() – Returns the type of the exception like, DML exception, list exception or Math exception.

Example

public class InvalidInputException extends Exception {
    public override string getMessage(){
        return 'Error Parsing: The character that you entered in invalid';
    }
}

As we can see that in this example we have simply created a new public class which extends Exception class. For every class that has been extended the methods which will be overridden have override keyword right after the access specifier. We have a method getMessage() which is overridden in this case and this message will provide the error string for the exception.

Output

The output of the error string will be something like this:

Searching for an experienced
Salesforce Company ?
Find out More

Support

That’s all for how to create custom exceptions, for any further queries feel free to add a ticket at:

https://webkul.uvdesk.com/en/customer/create-ticket/

Or let us know your views on how to make this code better, in comments section below.

. . .

Leave a Comment

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


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home

Table of Content