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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
