10

Is there a way to catch System.AssertException?

For example, some class is known to throw assertions in certain cases and it's ok to deal with that on some upper level. But unfortunately straightforward try-catch doesn't work for assert. I expect that this code will not throw an exception but it does:

try{
    System.assert(false, 'fail');
}catch(System.AssertException asEx){
    System.debug('success');
}

So, is there a way to implement ability of catching asserts?

7

Short answer no.

From the Apex Developers Guide:

Asserts that condition is true. If it is not, a fatal error is returned that causes code execution to halt. The returned error optionally contains the custom message specified in the last argument.

You can’t catch an assertion failure using a try/catch block even though it is logged as an exception.

You'll need to convert your asserts to exceptions if you want to handle them either at the point that they are thrown, or in any calling code.

  • 1
    Interesting though to create you own class for throwing catchable assertion exceptions as there are only 3 assert methods in the System class to replicate. And there is Test.isRunningTest(). – Keith C Apr 9 '14 at 8:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.