Style guide for throwing errors?


#1

Hi,

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.

#2

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.


#3

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?


#4

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


#5

I like ArgCheck.jl


#6

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


#7

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