内置函数显示生成错误
-
exit(Why)终止当前进程
-
throw(Why)抛出调用者可能要捕捉的异常
-
error(Why)崩溃性错误
try...catch
捕捉异常
try expression of
pattern when guard ->
body
catch
pattern when guard ->
body
after
body
end
try...catch
具有一个值
fun() [when guard] ->
body
try ... end
end
-module(try_test).
-compile(export_all).
generate_exception(1) -> a;
generate_exception(2) -> throw(a);
generate_exception(3) -> exit(a);
generate_exception(4) -> {'EXIT', a};
generate_exception(5) -> error(a).
demo1() ->
[catcher(I) || I <- [1,2,3,4,5]].
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.
demo2() ->
[{I, (catch generate_exception(I))} || I <- [1,2,3,4,5]].
demo3() ->
try generate_exception(5)
catch
error:X ->
{X, erlang:get_stacktrace()}
end.
lookup(N) ->
case(N) of
1 -> {'EXIT', a};
2 -> exit(a)
end.
重点是任其崩溃,永远不要在函数被错误参数调用时返回一个值,而是要抛出一个错误,假定调用者会修复这个错误。