1

This question already has an answer here:

I'm looking to see if there is a way to catch an assertion exception in apex and handle it gracefully. For instance, I have some number fields with a default value as 0. However, I'm hoping to use an assertion exception to ensure those values will never be null. I've done some searches so far and one post suggests creating a custom exception to handle this, but 'm not quite sure how this would resolve the issue. Is this even possible?

marked as duplicate by Adrian Larson apex May 1 '17 at 15:43

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • Exceptions to handle mundane logic are generally considered bad practice. Is there a reason why you don't want to use validation rule(s) here? – Derek F May 1 '17 at 15:39
  • 1
    I'm voting to reopen because, while the text of the question itself is a duplicate, there is another question that can be asked here. That question being "Are assertions or exceptions the right tool for this job?" – Derek F May 1 '17 at 15:46
  • 1
    @DerekF I recommend you edit the question to reflect the reason you suggest this question be reopened which I support on that basis. I'll add that just because a question has been asked before, that doesn't mean it isn't worthy of more than one answer, esp if the answer provides additional insight. – crmprogdev May 1 '17 at 16:46
2

No. A failed assertion is an automatic transaction abortion, just as if you'd violated a governor limit. You cannot try-catch AssertionException; if you must use an exception, throw a custom exception, but be aware that throwing an exception is a costly CPU operation (relatively, anyways), so it should only be used as a last resort.

1

No, AssertException is not catchable and should never be used in production code. If you need to throw an exception in your code, define a custom exception type:

class MyException extends Exception { }
...
    if (/*errorCondition*/) throw new MyException('error message');

And you can actually now throw standard exception types as well, so you could forego defining your own:

if (/*invalid inputs*/) throw new InvalidParameterValueException('Some informative message');

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