介绍
Erlang中的保护式是一类表达式,这里不详细介绍,可以看英文资料。
,
;
和 andalso
orelse
保护式中 ,
andalso
作用几乎相同, ;
orelse
作用几乎相同。这里用几乎而不是完全,理由如下。
参考资料 1:
Note: I’ve compared , and ; in guards to the operators andalso and orelse. They’re not exactly the same, though. The former pair will catch exceptions as they happen while the latter won’t. What this means is that if there is an error thrown in the first part of the guard X >= N; N >= 0, the second part can still be evaluated and the guard might succeed; if an error was thrown in the first part of X >= N orelse N >= 0, the second part will also be skipped and the whole guard will fail.
However (there is always a ‘however’), only andalso and orelse can be nested inside guards. This means (A orelse B) andalso C is a valid guard, while (A; B), C is not. Given their different use, the best strategy is often to mix them as necessary.
例子:
Erlang/OTP 19 [erts-8.2] [64-bit] [smp:4:4] [async-threads:10]
Eshell V8.2 (abort with ^G)
1> F = fun() when (a-1>0) ; true -> io:format("For Fun!~n") end.
#Fun<erl_eval.20.52032458>
2> F1 = fun() when (a-1>0) orelse true -> io:format("For Fun!~n") end.
#Fun<erl_eval.20.52032458>
3> F().
For Fun!
ok
4> F1().
** exception error: no function clause matching
erl_eval:'-inside-an-interpreted-fun-'()
5>
由此引申出一个结论: 保护式中的异常会被当做false处理。
逗号分号, ;
的保护式表达式,异常的作用域是 保护式中的单个布尔运算;andalso orelse
的保护式表达式,异常的作用域是 整个保护式。