Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rajatguptarg/e05c39492143def26a1bffa9716e3f79 to your computer and use it in GitHub Desktop.
Save rajatguptarg/e05c39492143def26a1bffa9716e3f79 to your computer and use it in GitHub Desktop.
Erlang exception handling example
-module(exceptions).
-export([sword/1, talk/0, black_knight/1]).
sword(1) -> throw(slice);
sword(2) -> erlang:error(cut_arm);
sword(3) -> exit(cut_leg);
sword(4) -> throw(punch);
sword(5) -> exit(cross_bridge).
talk() -> "blah blah".
black_knight(Attack) when is_function(Attack, 0) ->
try Attack() of
_ -> "None shall pass."
catch
throw:slice -> "It is but a scratch.";
error:cut_arm -> "I've had worse.";
exit: cut_leg -> "Come on you pansy!";
_:_ -> "Just a flesh wound."
end.
%% run these into the shell
1> c(exceptions).
{ok,exceptions}
2> exceptions:black_knight(fun exceptions:talk/0).
"None shall pass."
3> exceptions:black_knight(fun () -> exceptions:sword(1) end).
"It is but a scratch."
4> exceptions:black_knight(fun () -> exceptions:sword(2) end).
"I've had worse."
5> exceptions:black_knight(fun () -> exceptions:sword(3) end).
"Come on you pansy!"
6> exceptions:black_knight(fun () -> exceptions:sword(4) end).
"Just a flesh wound."
7> exceptions:black_knight(fun () -> exceptions:sword(5) end).
"Just a flesh wound."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment