Skip to content

Commit 61ce34e

Browse files
committed
Complete exercise 6.2.
1 parent d46fd68 commit 61ce34e

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

chapter_6/exercise_2/try_test.erl

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
-module(try_test).
2+
3+
-export([generate_exception/1, demo1/0, demo2/0, demo3/0, polite_and_detailed_messages/0]).
4+
5+
generate_exception(1) -> a;
6+
generate_exception(2) -> throw(a);
7+
generate_exception(3) -> exit(a);
8+
generate_exception(4) -> {'EXIT', a};
9+
generate_exception(5) -> error(a).
10+
11+
demo1() ->
12+
[catcher(I) || I <- [1,2,3,4,5]].
13+
14+
catcher(N) ->
15+
try generate_exception(N) of
16+
Val -> {N, normal, Val}
17+
catch
18+
throw:X -> {N, caught, throw, X};
19+
exit:X -> {N, caught, exited, X};
20+
error:X -> {N, caught, error, X}
21+
end.
22+
23+
demo2() ->
24+
[{I, (catch generate_exception(I))} || I <- [1,2,3,4,5]].
25+
26+
demo3() ->
27+
try generate_exception(5)
28+
catch
29+
error:X ->
30+
{X, erlang:get_stacktrace()}
31+
end.
32+
33+
% Exercise 6.2 says we need to provide two messages for each
34+
% exception. To do that I duplicated the catcher function above
35+
% and updated the return value so that is it always two tuples.
36+
% The first item in the tuple is a tuple representing the polite
37+
% error message for the user. The second is a tuple of four items
38+
% for the developer. The last item in the tuple is the stacktrace.
39+
polite_and_detailed_message(N) ->
40+
try generate_exception(N) of
41+
Val -> {Val, {N, normal, Val, erlang:get_stacktrace()}}
42+
catch
43+
throw:X -> {{caught_throw, X}, {N, caught, throw, X, erlang:get_stacktrace()}};
44+
exit:X -> {{caught_exit, X}, {N, caught, exited, X, erlang:get_stacktrace()}};
45+
error:X -> {{caught_error, X}, {N, caught, error, X, erlang:get_stacktrace()}}
46+
end.
47+
48+
% In order to demonstrate the polite_and_detailed_message
49+
% function, I created this function called
50+
% polite_and_detailed_messages. It is almost the same as
51+
% demo1/0.
52+
polite_and_detailed_messages() ->
53+
[polite_and_detailed_message(I) || I <- [1,2,3,4,5]].

0 commit comments

Comments
 (0)