# raise error on type mismatch

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 GeneralUtilitiesWithMessageHandler. 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)?

• 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. – bill s Nov 8 '18 at 19:22
• @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. – Alan Nov 8 '18 at 19:42
• 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. – bill s Nov 8 '18 at 21:16
• 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. – Alan Nov 8 '18 at 22:04