aboutsummaryrefslogtreecommitdiff
path: root/learn-you-some-erlang/exceptions.erl
diff options
context:
space:
mode:
Diffstat (limited to 'learn-you-some-erlang/exceptions.erl')
-rw-r--r--learn-you-some-erlang/exceptions.erl76
1 files changed, 76 insertions, 0 deletions
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).