Does Julia have the Python equivalent of ValueError?

In Python, a specific exception exists called ValueError:

Raised when an operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError .

Does Julia have such an exception?

I typically use:

help?> ArgumentError
search: ArgumentError

  ArgumentError(msg)

  The parameters to a function call do not match a valid signature. Argument
  msg is a descriptive error string.

in this case.

ArgumentError is apparently for cases when the types are wrong, but ValueError is for when the values are inappropriate, so it doesn’t seem to quite fit.

1 Like

I see two options, throw error() with a detailed error message and document it or create the ValueError exception, and use it.

struct ValueError <: Exception 
    ...
end 
1 Like

When types are wrong you will get MethodError as Julia will not find a matching method for your call.

1 Like

DomainError is used for this (for some mathematical functions like sqrt, log etc at least):

julia> sqrt(-1)
ERROR: DomainError with -1.0:
sqrt will only return a complex result if called with a complex argument.
Try sqrt(Complex(x)).
Stacktrace:
8 Likes

Good point.

But then what’s up with this docstring?

The parameters to a function call do not match a valid signature.

I agree this is a bit fuzzy. I know the practice, which is (just some examples):

julia> Dates.Date(0,0,0)
ERROR: ArgumentError: Month: 0 out of range (1:12)

julia> parse(Int, 'a')
ERROR: ArgumentError: invalid base 10 digit 'a'

julia> parse(Int, "a")
ERROR: ArgumentError: invalid base 10 digit 'a' in "a"

julia> Symbol("ab\0")
ERROR: ArgumentError: Symbol name may not contain \0

and my favorite:

julia> Base.notnothing(nothing)
ERROR: ArgumentError: nothing passed to notnothing

which is defined as:

notnothing(::Nothing) = throw(ArgumentError("nothing passed to notnothing"))

which contradicts the interpretation from the docstring in 100% :smiley:.

The practice I use in DataFrames.jl:

  1. DomainError - when working with mathematical functions kind of stuff;
  2. ArgumentError - all else

In theory (if we read the docstring precisely) ArgumentError should be probably used when there is e.g. ::Any in the signature, but we dynamically check the type within the body of the function, but AFAICT this is not its typical use case in practice.

You also have BoundsError which is also kind of DomainError but specific for indexing operations.

5 Likes

I just make a PR to fix this: clarify ArgumentError docstring by stevengj · Pull Request #41177 · JuliaLang/julia · GitHub

3 Likes

I take it that ArgumentError is what I should use, correct?

My opinion, as I have commented above, is that ArgumentError is often used in such cases. You can also use DomainError as @fredrikekre suggested - depending on what you feel is more appropriate in your case.

1 Like