Historically, parse was created before tryparse in Julia. However, tryparse is more fundamental and generally useful, since it allows the caller to handle badly formatted strings. The caller can then decide whether to error or handle the input in another way. By erroring when nothing is returned, tryparse can easily be turned into parse - but it is not easy the other way around.
I propose that we:
- Define
parse in terms of tryparse by adding the following fallback definition:
function parse(::Type{T}, s::AbstractString) where T
y = tryparse(T, s)
y === nothing && throw(ArgumentError("Cannot parse as $T: \"$s\""))
return y
end
- Recommend users to implement
tryparse(::Type{T}, s::AbstractString) and only implement parse if they need a custom error message.
This way, the user gets both parse and tryparse, only having to implement one function, and as an added bonus, we emphasize that users should implement the more efficient tryparse as the primary mechanism.
Historically,
parsewas created beforetryparsein Julia. However,tryparseis more fundamental and generally useful, since it allows the caller to handle badly formatted strings. The caller can then decide whether to error or handle the input in another way. By erroring whennothingis returned,tryparsecan easily be turned intoparse- but it is not easy the other way around.I propose that we:
parsein terms oftryparseby adding the following fallback definition:tryparse(::Type{T}, s::AbstractString)and only implementparseif they need a custom error message.This way, the user gets both
parseandtryparse, only having to implement one function, and as an added bonus, we emphasize that users should implement the more efficienttryparseas the primary mechanism.