1. try ... catch 句型
try FuncOrExpressionSequence of Pattern1 [when Guard1] -> ExpressionBody1; Pattern2 [when Guard2] -> ExpressionBody2 catch [ExceptionType:]ExceptionPattern1 [when ExceptionGuardSeq1] -> ExceptionBody1; [ExceptionType:]ExceptionPatternN [when ExceptionGuardSeqN] -> ExceptionBodyN after AfterExpressions end.
- try ... catch 工作原理
- 对 FuncOrExpressionSequence 先求值
- 如果不产生异常,那么它的返回值就对模式Pattern1, Pattern2... 进行模式匹配。如果匹配成功,模式之后的表达式的值就是 try ... catch 的返回值
- 如果产生异常,就会逐个匹配 catch 下的 Expattern1 等模式。ExceptionType 是原子throw,exit 或 error 中的一个。未标明 ExceptionType,默认为 throw.
- 如果不产生异常,那么它的返回值就对模式Pattern1, Pattern2... 进行模式匹配。如果匹配成功,模式之后的表达式的值就是 try ... catch 的返回值
- after 为可选项,它后面的代码,用于执行完 FuncOrExpressionSequence 后的清理工作。无论是否抛出异常,这段代码一定都会被执行。
- 对 FuncOrExpressionSequence 先求值
- 举例
demol() -> [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. 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). % output: % [{1, normal, a}, % {2, caught, thrown, a}, % {3, caught, exited, a}, % {4, normal, {'Exit', a}}, % {5, caught, error, a}]
- 捕获所有可能异常
- try Expr
- catch
- _:_ -> ...
- end.
2. To-Be-Added...