Erlang(四)顺序程序的错误处理

内置函数显示生成错误

  • exit(Why)终止当前进程

  • throw(Why)抛出调用者可能要捕捉的异常

  • error(Why)崩溃性错误

try...catch捕捉异常

  1. try expression of
  2. pattern when guard ->
  3. body
  4. catch
  5. pattern when guard ->
  6. body
  7. after
  8. body
  9. end

try...catch具有一个值

  1. fun() [when guard] ->
  2. body
  3. try ... end
  4. end
  5. -module(try_test).
  6. -compile(export_all).
  7. generate_exception(1) -> a;
  8. generate_exception(2) -> throw(a);
  9. generate_exception(3) -> exit(a);
  10. generate_exception(4) -> {'EXIT', a};
  11. generate_exception(5) -> error(a).
  12. demo1() ->
  13. [catcher(I) || I <- [1,2,3,4,5]].
  14. catcher(N) ->
  15. try generate_exception(N) of
  16. Val -> {N, normal, Val}
  17. catch
  18. throw:X -> {N, caught, thrown, X};
  19. exit:X -> {N, caught, exited, X};
  20. error:X -> {N, caught, error, X}
  21. end.
  22. demo2() ->
  23. [{I, (catch generate_exception(I))} || I <- [1,2,3,4,5]].
  24. demo3() ->
  25. try generate_exception(5)
  26. catch
  27. error:X ->
  28. {X, erlang:get_stacktrace()}
  29. end.
  30. lookup(N) ->
  31. case(N) of
  32. 1 -> {'EXIT', a};
  33. 2 -> exit(a)
  34. end.

重点是任其崩溃,永远不要在函数被错误参数调用时返回一个值,而是要抛出一个错误,假定调用者会修复这个错误。

erlang9