1
$\begingroup$

Is there a best practice for raising an error on a type mismatch? For compiled functions I'm guessing the answer is the use of GeneralUtilities`WithMessageHandler. For ordinary pattern-based functions, is there a better alternative than providing each function with a custom test for precondition satisfaction (as in this answer to a closely related question)?

$\endgroup$
  • $\begingroup$ Most things are not typed in Mathematica. One way to make sure that things only get the right kind of data is by specifying conditions when defining functions. For example, use g[x_?NumberQ] := x^2 instead of g[x_]:=x^2. $\endgroup$ – bill s Nov 8 '18 at 19:22
  • $\begingroup$ @bills My question presumes pattern-based type checking of the sort you illustrate. If you apply your function to a non-number, it does not raise an error. See the answer link I provided in the question. $\endgroup$ – Alan Nov 8 '18 at 19:42
  • $\begingroup$ So you want an error. How about this: g[x_?NumberQ] := x^2; g[x_] := Print["error"]; Now g[4] gives 16 and g["four"] gives "error", or whenever the NumberQ type is not matched. $\endgroup$ – bill s Nov 8 '18 at 21:16
  • $\begingroup$ Yes, I realize that it may seem odd to want a runtime error, but it can protect against bad arguments propagating in long-running computations. You are proposing to pass through to a default pattern and then do something. (I would Throw rather than Print, because a Null might still propagate.) This falls in the category of "custom test for precondition satisfaction" and is thereby a variant of the answer I link to. I am open to the argument that something along this line is best practice. $\endgroup$ – Alan Nov 8 '18 at 22:04

Your Answer

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

Browse other questions tagged or ask your own question.