Can Built-In Exceptions Be Thrown?

In Creating Custom Exceptions, the documentation still claims:

Since you can’t throw built-in Apex exceptions but can only catch them, you can create custom exceptions to throw in your methods.

Is it still true that built-in Exception types cannot be thrown?

Answer

As far as I know, @mattandneil was the first to discover this change in this answer to a question by @DanielBallinger.

Despite the documentation’s claims to the contrary, the compiler now allows built-in Exception types to be constructed. I confirmed through Execute Anonymous with the following snippet:

try
{
    CalloutException e = new CalloutException();
    e.setMessage('This is a constructed exception!');
    throw e;
}
catch (Exception pokemon)
{ // gotta catch em all!
    system.debug(pokemon);
}

I went through the whole list and what do you know? The following types can all be constructed and thrown:

  • AsyncException
  • CalloutException
  • DmlException
  • EmailException
  • ExternalObjectException
  • InvalidParameterValueException
  • LimitException (though it still can’t be caught)
  • JSONException
  • ListException
  • MathException
  • NoAccessException
  • NoDataFoundException
  • NoSuchElementException
  • NullPointerException
  • QueryException
  • RequiredFeatureMissingException
  • SearchException
  • SecurityException
  • SerializationException
  • SObjectException
  • StringException
  • TypeException
  • VisualforceException
  • XmlException

I must admit it feels weird that you can throw new LimitException(). I submitted Feedback on the linked documentation requesting that they update their content.

Attribution
Source : Link , Question Author : Adrian Larson , Answer Author : Matt and Neil

Leave a Comment