typestar

try/catch en Erlang

Tres clases de error: throw, error y exit, atrapadas por nombre.

%% try/catch names the class; throw, error, and exit differ.
risky(bad_number) ->
    throw(unlisted);
risky(cut_line) ->
    error(no_circuit);
risky(Line) ->
    {connected, Line}.

attempt(Input) ->
    try risky(Input) of
        {connected, L} -> io:format("Through on ~p~n", [L])
    catch
        throw:unlisted -> io:format("Not in the book~n");
        error:no_circuit -> io:format("Dead pair, reroute~n")
    end.

main(_) ->
    [attempt(X) || X <- [4, bad_number, cut_line]],
    ok.

Cómo funciona

  1. try ... of maneja el éxito; catch maneja las clases.
  2. throw:unlisted y error:no_circuit matchean clase y razón.
  3. Las entradas sanas fluyen normal por el brazo of.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
19
Caracteres a escribir
440
Tokens
127
Ritmo de tres estrellas
60 tpm

Al ritmo de tres estrellas de 60 tokens por minuto, este intento toma unos 127 segundos.

Escribe este fragmento

Paso 2 de 2 en Errores como datos; paso 24 de 31 en Fundamentos del lenguaje.

← Anterior Siguiente →

try/catch en otros lenguajes