typestar

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

  1. tryparse returns nothing instead of throwing.
  2. throw(ArgumentError(...)) and error(...) raise.
  3. catch err sees the exception; typeof(err) names it.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Idioms, step 21 of 27 in Language basics.

← Previous Next →

Errors in other languages