The Silver Lining

Lessons & Learnings from a salesforce certified technical architect.

Throwing Custom Apex Exceptions

with 4 comments

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.

Advertisement

Written by Wes

June 11, 2009 at 8:46 am

4 Responses

Subscribe to comments with RSS.

  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.

    Nisha

    April 11, 2012 at 5:54 am

    • 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?

      Wes

      April 11, 2012 at 10:40 am

      • Wes, did you write a testcalss for myException ?

        Karma

        May 21, 2012 at 5:18 pm

  2. throw the test coverage on the Exception extension does not go up (0%).

    Karma

    May 21, 2012 at 5:20 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: