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
try ... ofhandles success;catchhandles the classes.throw:unlistedanderror:no_circuitmatch class and reason.- Untouched inputs flow through the
ofarm normally.
Keywords and builtins used here
attemptcatchendformatmainofriskytry
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.
Step 2 of 2 in Errors as data, step 24 of 31 in Language basics.