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.
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
throw the test coverage on the Exception extension does not go up (0%).
Karma
May 21, 2012 at 5:20 pm