Best way to enforce argument requirements (assert vs. exception, or something else)?

I have a function that expects a positive number as argument, for example:

f(x) = sqrt(x)

I want to be safe about this, so I want to throw an error if x < 0. Currently I do an assert:

function f(x)
  @assert x >= 0
  sqrt(x)
end

Is this the recommended way? Or should I throw an error instead? Are there guidelines for this?

1 Like

No.

Yes, but not an error most of the time.

https://docs.julialang.org/en/latest/manual/control-flow/#Built-in-Exceptions-1 and the multiple entries following https://docs.julialang.org/en/latest/stdlib/base/#Core.ArgumentError tells you when to use which excepiton type.

3 Likes

Also see

2 Likes

This comes up high in google searches. It’s a pretty good FAQ.

Reference links to the manual are dead. I think these are the new ones:

https://docs.julialang.org/en/v1/base/base/#Errors

https://docs.julialang.org/en/v1/manual/control-flow/

1 Like