Finding which var is an invalid type when initialising a struct

Note that (I haven’t checked, but I’m pretty sure) all of those cases in Base are thrown when it’s impossible to let dispatch handle it, i.e. when the argument provided is a valid instance of the type it is, but it’s nevertheless not suitable for the called function. A good example is this, where a valid Int has been passed but it’s not in the range of acceptable values. This is different from the cases presented in this thread, where it’s a specific Type that isn’t wanted, for which MethodError is more applicable (though throwing it yourself is bad, which is why I suggested ArgumentError above instead).

Maybe the docstring of ArgumentError could be amended to clarify this nuance - I’ll see if I can find the time to make a PR tomorrow.

I do agree that explicitly throwing MethodError ala throw(MethodError("...")) is very bad form and the (I think) only place in Base where this was the case has been removed since. That’s also not what I’m arguing for here though - I’m proposing to annotate the types in the constructor, which will result in a MethodError all on its own.

Regardless of throwing MethodError explicitly or not, in either case the stacktrace will have the offending call in it, and following it is very much standard debugging practice.

1 Like

While I see now that we agree on more than it seemed to me reading your last post, I yet disagree on one point: passing some type of object as an argument to the constructor can be a common error, and you may want to have a method that allow such input just to spew an ArgumentError giving specific guidance on that (or you may want to block some specific case to avoid confusion, like allowing Numbers but not Bool which is a Number). But maybe, the right way to deal with that is the Base.Experimental.register_error_hint I mentioned before.

1 Like