# Is there an easy way to make built-in functions do a replacement before throwing an error message?

Many built-in functions throw errors before executing a ReplaceAll. The functions still execute the ReplaceAll as intended, but the spurious errors are a nuisance. I can avoid this problem using ReleaseHold and Hold, but there's probably a better way.

Here's one of many examples:

RandomVariate[NormalDistribution[20, 10]]
(* 5.2037 *)

RandomVariate[NormalDistribution[μ, σ]] /. {μ -> 20, σ -> 10}
(* During evaluation of In[67]:= RandomVariate::posprm: Parameter σ
at position 2 in NormalDistribution[μ,σ] is expected to be positive. *)
(* 6.78478 *)

ReleaseHold[Hold[RandomVariate[NormalDistribution[μ, σ]]] /. {μ -> 20, σ -> 10}]
(* 46.4181 *)

• Just Quiet should do the trick. But, I have two questions. Firstly, how do you know that you will always have the values of mu and sigma handy when the error message is thrown? Secondly, if you intend to invoke RandomVariate only after you have computed the values of mu and sigma, why not do something like {20, 10} // Apply[NormalDistribution /* RandomVariate]? In other words, why not first assemble all the atomic values that you need and then apply the appropriate heads? Jan 12 at 1:24
• You could also wrap the relevant code in a With, Block, or Module containing the appropriate definition for mu and sigma. Jan 12 at 3:03
• You may force MMA to do the replacement by: RandomVariate[ Evaluate[ NormalDistribution[\[Mu], \[Sigma]]] /. {\[Mu] -> 20, \[Sigma] -> 10}] Jan 12 at 7:59
• It is the evaluation order of Mathematica that is in your way; you can read a lot about it in the tech note on Evaluation Control. There are multiple ways to do this, as already mentioned by others in the comments, for example, for your case, you could also use Unevaluated: Unevaluated@RandomVariate[NormalDistribution[μ, σ]] /. {μ -> 20, σ -> 10}. Jan 12 at 13:45
• The Quiet[] idea has the problem of silencing desired errors. The others (With, Block, Module, Apply and Unevaluated) are all good, simple solutions. Thanks, MarcoB, Daniel Huber, Shredderroy and Domen. Jan 12 at 15:35