[SF1] Apex Exceptions for Fun and Profit

In the run up to Dreamforce, I'm working on a project that I can't talk much about until the big show itself. Actually, I'm working on several things that I can't talk about until the big show ... and that often makes blogging about Force.com development a bit difficult. However, one of the projects has me writing considerably more Anonymous Apex than I have before and I just stumbled on a quick trick I thought I would share.

My two normal use cases for Anonymous Apex are to create sample data for testing and to put code through some paces. In the first case, I want the data I use to stick around - but in the latter, I really don't. I'm basically writing something in between a unit test and a debug script and so I want to be able to track what happens ... but I don't need anything permanent to come out of it.

For proper unit testing, that isn't a big deal. All the DML is transient. For Anonymous Apex, I'm going a slightly different route.

Apex allows you to create custom exceptions - something I haven't really needed to use except in a few isolated cases in the past. However it is incredibly useful for the scenario above.

This is because I can create a new exception:

public class MyException extends Exception{}

And since by inheriting Exception, you can add your own error message ... I can use the exception for both success and error scenarios. A la:

Account a = new Account(Name='TestCo');
insert a;
a = RandomTestClass.InterestingLogic(a);
update a;
if(a.Name == RandomTestClass.outcome) {
    throw MyException('success');
} else {
    throw MyException('RandomTestClass Fail')

When that runs, I will be able to hit the debug logs and see one of the two exception messages being reported. However, in either scenario - the DML will be rolled back because the execution counts as a failure. This allows me to continue to adjust my logic without having to worry about any kind of test data cleanup.

You can read more about custom exceptions in the docs below.

Update, As Alan points out in the comments below - you can use assert functions in Anonymous Apex now. I hadn't tried that route because I'm pretty certain at one point they were only allowed in test context (like RunAs). So alternate path to pass/fail while rolling back DML would be to stack assertions, i.e.:

Account a = new Account(Name='TestCo');
insert a;
a = RandomTestClass.InterestingLogic(a);
update a;

System.assertEquals(a.Name, RandomTestClass.outcome);

System.assert(false, 'success - rolling back');

Lesson 5: Custom Exceptions

comments powered by Disqus