[erlang-questions] is this try expression idiom common?

Richard Carlsson <>
Wed Nov 12 09:11:25 CET 2008


Kevin wrote:
> Whether its the pragmatic book or the online docs, the impression I've 
> always gotten about try..catch expressions is this
> 
> try FuncOrExpressionSequence of
> Pattern1 [when Guard1] -> Expressions1;
> Pattern2 [when Guard2] -> Expressions2;
> catch
> ExceptionType1: ExPattern1 [when ExGuard1] -> ExExpressions1;
> ExceptionType2: ExPattern2 [when ExGuard2] -> ExExpressions2;
> end
> 
> In fact the pragmatic book calls try...catch "like a case expression on 
> steroids. It’s basically a case
> expression with catch and after blocks at the end."
> 
> So, to a newbie like me, I've always assumed you needed case like 
> pattern matchers inside the try. This was seriously cramping my style. 

Well, the Reference Manual in the online docs describe the version
without "of" as a first example, and only later mentions that "The
try expression can have an 'of' section". Perhaps it is presented
differently in the book.

> To me this is a completely different idiom, absolutely nothing like a 
> case expression, and opens erlang up to a more exception based control 
> flow and error handling. Is this legit? Frowned upon? I searched the 
> pragmatic book and there is not a single example of this.

There is nothing particularly strange about it; just a shorthand for

  try ... of
    X -> X
  catch
    _Class:_Term -> something_failed
  end.

i.e., "if it succeeds, just return whatever the body returned",
just like 'case ... of X -> X end'. But 'try' is definitely
a full-blown exception handling mechanism, that can be used and
abused in many ways. Compared to the rest of the language, 'try'
is a relatively new construct (the old 'catch Expr' construct was
much too weak), and as a consequence, the Erlang community has
not had so much time to develop a set of common conventions for
when and how exceptions should be used. But it is certainly
"legit" - that's why we added a better mechanism for it.

    /Richard



More information about the erlang-questions mailing list