Erlang / Erlang Advanced Interview questions
When should you use throw instead of returning an {error, Reason} tuple?
Both signal "this didn't work," but they fit different shapes of control flow. A tagged
{error, Reason} return keeps the failure visible in the function's ordinary return value, forcing
every caller to explicitly pattern-match and decide what to do — it composes naturally with Erlang's
usual "match on the result" style and is easy to trace just by reading the function's uses.
%% error tuple: caller must explicitly handle both branches case validate(Input) of {ok, Value} -> proceed(Value); {error, Reason} -> reject(Reason) end. %% throw: useful for bailing out from deep inside nested helper calls validate_all(Items) -> try [validate_one(I) || I <- Items] catch throw:{invalid, Item} -> {error, {invalid, Item}} end.
throw earns its keep specifically when you're several calls deep inside a purely internal
helper chain and want to bail out immediately to one handler at the top, without threading an
{error, Reason} check through every intermediate function in between. It should stay internal to
code you also control the corresponding catch for, rather than being part of a module's public
API contract, where a tagged tuple is the more discoverable, idiomatic choice.
More Related questions...