typestar

try/catch in Erlang

Three error classes: throw, error, and exit, caught by name.

%% 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.

How it works

  1. try ... of handles success; catch handles the classes.
  2. throw:unlisted and error:no_circuit match class and reason.
  3. Untouched inputs flow through the of arm normally.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
440
Tokens
127
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 127 seconds.

Type this snippet

Step 2 of 2 in Errors as data, step 24 of 31 in Language basics.

← Previous Next →

try/catch in other languages