Style guide for throwing errors?



I have two questions about programming style and errors in Julia:

  1. Is it considered good style to have functions validate their inputs, and throw informative errors if an input’s value would cause an error?
  2. What type of error should be thrown in that case? I have been using ArgumentError but when I look at the documentation, it seems like ArgumentError may have been intended for situations where no method matching the type signature at the call site was found.


I think yes. But exploit also types. That is, instead of throwing an error if x is not of type T, define your function to take argument x::T explicitly.

I think that’s MethodError.
You might also take a look at DomainError, if your function is a math function.


So ArgumentError is an ok error to throw if, for example, a function requires an argument to be positive, but a negative value is received?


I think so. Or DomainError. For example sqrt(-2) throws a DomainError, which is more appropriate if the mathematical definition of “domain” applies to your function.

You can see some examples of ArgumentError usage by the pros in the source of Julia itself


I like ArgCheck.jl


Man, where has ArgCheck.jl been all my life? Thanks for the tip!


I had forgotten about ArgCheck! It’s very nice.