Trapping an Exception with try…catch

If you’re familiar with Java, then you’ll have no difficulties understanding the trycatch expression. Java can trap an exception with the following syntax:

 
try​ {
 
block
 
} ​catch​ (exception type identifier) {
 
block
 
} ​catch​ (exception type identifier) {
 
block
 
} ... ​
 
finally​ {
 
block
 
}

Erlang has a remarkably similar construct, which looks like this:

 
try​ FuncOrExpressionSeq ​of
 
Pattern1 [​when​ Guard1] -> Expressions1;
 
Pattern2 [​when​ Guard2] -> Expressions2;
 
...
 
catch
 
ExceptionType1: ExPattern1 [​when​ ExGuard1] -> ExExpressions1;
 
ExceptionType2: ExPattern2 [​when​ ExGuard2] -> ExExpressions2;
 
...
 
after
 
AfterExpressions
 
end

try…catch Has a Value

Remember, ...

Get Programming Erlang, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.