try…catch
-module(try_test).
-export([demo1/0]).
generate_exception(1) -> a;
generate_exception(2) -> throw(a);
generate_exception(3) -> exit(a);
generate_exception(4) -> {'EXIT',a};
generate_exception(5) -> erlang:error(a).
demo1() ->
[catcher(I) || I<-[1,2,3,4]].
catcher(N) ->
try generate_exception(N) of
Val -> {N,normal,Val}
catch
throw:X -> {N,caught,thrown,X};
exit:X -> {N,caught,exited,X};
error:X -> {N,caught,error,X}
end.
1> c(try_test).
{ok,try_test}
2> try_test:demo1().
[{1,normal,a},
{2,caught,thrown,a},
{3,caught,exited,a},
{4,normal,{'EXIT',a}}]
catch
demo2() ->
[{I,(catch generate_exception(I))} || I<-[1,2,3,4,5]].
1> c(try_test).
{ok,try_test}
2> try_test:demo2().
[{1,a},
{2,a},
{3,{'EXIT',a}},
{4,{'EXIT',a}},
{5,
{'EXIT',{a,[{try_test,generate_exception,1,
[{file,"try_test.erl"},{line,7}]},
{try_test,'-demo2/0-lc$^0/1-0-',1,
[{file,"try_test.erl"},{line,22}]},
{try_test,'-demo2/0-lc$^0/1-0-',1,
[{file,"try_test.erl"},{line,22}]},
{erl_eval,do_apply,6,[{file,"erl_eval.erl"},{line,674}]},
{shell,exprs,7,[{file,"shell.erl"},{line,687}]},
{shell,eval_exprs,7,[{file,"shell.erl"},{line,642}]},
{shell,eval_loop,3,[{file,"shell.erl"},{line,627}]}]}}}]
栈跟踪
demo3() ->
try generate_exception(5)
catch
error:X ->
{X,erlang:get_stacktrace()}
end.
1> c(try_test).
{ok,try_test}
2> try_test:demo3().
{a,[{try_test,generate_exception,1,
[{file,"try_test.erl"},{line,7}]},
{try_test,demo3,0,[{file,"try_test.erl"},{line,25}]},
{erl_eval,do_apply,6,[{file,"erl_eval.erl"},{line,674}]},
{shell,exprs,7,[{file,"shell.erl"},{line,687}]},
{shell,eval_exprs,7,[{file,"shell.erl"},{line,642}]},
{shell,eval_loop,3,[{file,"shell.erl"},{line,627}]}]}
作者 Github : tojohnonly , 博客 : EnskDeCode