Throwing Custom Apex Exceptions

Throwing custom exceptions is something that most Java developers expect to be able to do when working with Apex code, and indeed it is possible. It isn’t very well documented, but I managed to stumble across this solution after some experimentation.

Usually, I would expect an exception to be thrown using syntax at least similar to:

throw new Exception('Don\'t be a silly user.');

However this syntax will give the follow error: Type cannot be constructed: Exception

Instead you have to create a new exception class with extends the Apex Exception class:

public class myException extends Exception {}

And then throw that new exception:

throw new myException('Don\'t be a silly user.');

That’s just the beginning of course, you could create some pretty fancypants error handling in your custom exceptions. The world is your oyster, now all your need is some Tabasco and lime.

6 thoughts on “Throwing Custom Apex Exceptions”

  1. i have implement this code in my class. but i have called this in asynchronous class and trigger and now i need to show this message. but its not working.

    Reply
    • It’s _probably_ because you are trying to access an asynchronous result from synchronous code (or vice versa). Remember that when you fire an asynch call that code gets it’s own “thread” and operates in it’s own transaction. So the synchronous and asychronous code no longer “know” about eachother. Make sense?

      Reply
    • Hi, I have the same problem and no answers or documentation on how to test a custom exception class. Salesforce requires code coverage to deploy the custom exception class but no matter what I do my test class for the exception refuses to raise the coverage. It stays 0%. Can anyone help with this???!!! So frustrating.

      Reply
      • Ok so I found the solution. Add a property or a method to the custom exception class and call that property/method and you will get full code coverage. Hacky but that is the only way I can see it working.

        Reply

Leave a Comment