Errores en Julia
tryparse para el fallo esperado, throw/try/catch para el resto.
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
Cómo funciona
tryparsedevuelvenothingen vez de lanzar.throw(ArgumentError(...))yerror(...)lanzan.catch errve la excepción;typeof(err)la nombra.
Palabras clave y builtins usados aquí
ArgumentErrorFloat64catchendforfunctioninnothingreturntry
El intento, en números
- Líneas
- 15
- Caracteres a escribir
- 380
- Tokens
- 92
- Ritmo de tres estrellas
- 65 tpm
Al ritmo de tres estrellas de 65 tokens por minuto, este intento toma unos 85 segundos.
Paso 3 de 3 en Idiomas del lenguaje; paso 21 de 27 en Fundamentos del lenguaje.