Using custom exception types
Salesforce allows developers to extend the standard Apex Exception
class to build custom exceptions that can provide bespoke errors and messages. To create a custom exception class, simply extend the standard Exception
class as follows:
public with sharing class CustomisedException extends Exception { }
We can throw an exception of our new type using the throw
keyword:
throw new CustomisedException('This is the exception message`);
Custom exception classes allow us a greater degree of control over the messages that are displayed within exceptions that are thrown and can also allow us to take action in throwing an exception when one would not typically be thrown or be thrown incorrectly.
Consider the following code, which is making a callout to a RESTful web service and receives a status code back that is not a 200 OK
code. Apex code will not error here (nor should it by default), however, we need to ensure that...