[erlang-questions] Exceptions in guards are blocked. Why?

Serge Aleynikov saleyn@REDACTED
Thu Jan 29 14:35:56 CET 2009


The evaluation order or (A or B) is not defined.  In this case the 
second part of the guard is evaluated first and fails.  Use orelse for 
deterministic order, or better (for reasons indicated here [1]), split 
it into two pattern matches:

fun(X) when (X == 0) orelse (X / 0 > 2) -> true; (_) -> false end.

or

fun(0) -> ...;
    (X) when X / 0 > 2 -> ...;
    ...
end.

Note that since guard expressions don't have side effects, X / 0 > 2 
will not throw an exception but the guard would invalidate the pattern 
match on X.  You can verify it with:

if X / 0 > 2 -> true;
_ -> false
end.

Serge

[1] http://www.erlang.org/eeps/eep-0017.html

Alexander Semenov wrote:
> Hi, folks,
> 
> Can you explain me why exceptions are blocked in guards?
> For example I wrote this in erlang shell:
> 
> F = fun(X) when (X == 0) or (X / 0 > 2) -> true; (_) -> false end.
> F(0).
> false
> 
> Is this cause of 'side effects free' guards nature?




More information about the erlang-questions mailing list