Reading — step 1 of 5
Learn
~1 min readErrors and Supervision
Erlang has TWO error-handling modes: return tagged tuples for expected failures, throw exceptions for unexpected ones.
Tagged tuple convention:
parse_int(S) ->
case string:to_integer(S) of
{error, _} -> {error, not_a_number};
{N, _} -> {ok, N}
end.
%% Caller:
case parse_int("42") of
{ok, N} -> use(N);
{error, Reason} -> log(Reason)
end
This is the dominant Erlang style. Most stdlib functions return {ok, X} / {error, Reason}.
Exceptions with throw, error, exit:
throw(my_problem) %% domain error you expect to be caught
error(badmatch) %% bug — runtime error
exit(killed) %% terminate the process
try/catch:
try
risky_operation(X)
catch
throw:my_problem -> handle();
error:badarg -> log_bug();
exit:Reason -> shutdown(Reason)
after
cleanup() %% always runs
end
The pattern is Class:Reason — three classes are throw, error, exit.
The Erlang philosophy: "let it crash."
- Don't write defensive code for impossible cases
- Wrap risky code in a process with a supervisor
- When a process crashes, the supervisor restarts it from a known good state
- This is faster, simpler, and more reliable than try/catch everywhere
erlang:link/1 ties two processes together — when one dies, the other is notified (or also dies, by default).
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…