From 5a9cdd3cc89507d4d74f8bded56ce5e037b3b56e Mon Sep 17 00:00:00 2001 From: Trygve Laugstøl Date: Fri, 23 Feb 2024 07:08:18 +0100 Subject: wip --- learn-you-some-erlang/exceptions.erl | 76 ++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 learn-you-some-erlang/exceptions.erl (limited to 'learn-you-some-erlang/exceptions.erl') diff --git a/learn-you-some-erlang/exceptions.erl b/learn-you-some-erlang/exceptions.erl new file mode 100644 index 0000000..0ed6742 --- /dev/null +++ b/learn-you-some-erlang/exceptions.erl @@ -0,0 +1,76 @@ +-module(exceptions). +-compile(export_all). + +throws(F) -> + try F() of + _ -> ok + catch + Throw -> {throw, caught, Throw} + end. + +errors(F) -> + try F() of + _ -> ok + catch + error:Error -> {error, caught, Error} + end. + +exits(F) -> + try F() of + _ -> ok + catch + exit:Exit -> {exit, caught, Exit} + end. + +sword(1) -> throw(slice); +sword(2) -> erlang:error(cut_arm); +sword(3) -> exit(cut_leg); +sword(4) -> throw(punch); +sword(5) -> exit(cross_bridge). + +%%"I must cross this bridge" +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. +%"We'll call it a draw..." + +talk() -> "blah blah". + +whoa() -> + try + talk(), + _Knight = "None shall Pass!", + _Doubles = [N*2 || N <- lists:seq(1,100)], + throw(up), + _WillReturnThis = tequila + of + tequila -> "hey this worked!" + catch + Exception:Reason -> {caught, Exception, Reason} + end. + +im_impressed() -> + try + talk(), + _Knight = "None shall Pass!", + _Doubles = [N*2 || N <- lists:seq(1,100)], + throw(up), + _WillReturnThis = tequila + catch + Exception:Reason -> {caught, Exception, Reason} + end. + +catcher(X,Y) -> + case catch X/Y of + {'EXIT', {badarith,_}} -> "uh oh"; + N -> N + end. + +one_or_two(1) -> return; +one_or_two(2) -> throw(return). -- cgit v1.2.3