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

Alexander Semenov bohtvaroh@REDACTED
Thu Jan 29 14:44:55 CET 2009


Thanks, that's all I would know.

On Thu, 2009-01-29 at 08:35 -0500, Serge Aleynikov wrote:
> 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?
> 
-- 
Alexander Semenov <bohtvaroh@REDACTED>




More information about the erlang-questions mailing list