Errors in Julia
tryparse for expected failure, throw/try/catch for the rest.
function parse_altitude(raw)
alt = tryparse(Float64, raw)
# nothing is the sentinel; throw raises a real exception.
alt === nothing && throw(ArgumentError("unreadable: $raw"))
alt < 0 && error("below the horizon: $alt")
return alt
end
for raw in ["47.5", "n/a", "-10"]
try
println("Altitude ", parse_altitude(raw))
catch err
println("Skipped ($(typeof(err))): ", err.msg)
end
end
How it works
tryparsereturnsnothinginstead of throwing.throw(ArgumentError(...))anderror(...)raise.catch errsees the exception;typeof(err)names it.
Keywords and builtins used here
ArgumentErrorFloat64catchendforfunctioninnothingreturntry
The run, in numbers
- Lines
- 15
- Characters to type
- 380
- Tokens
- 92
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 85 seconds.
Step 3 of 3 in Idioms, step 21 of 27 in Language basics.