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
ExceptionTypes are throw/1
, error/1
and exit/1
.
Shorthand:
try F
catch _:_ -> SaveExpression
after Cleaning
Ultimate shorthand, which ignores error/1
and exit/1
and behaves like catch _ -> ...
:
catch F
Example
[{I, (catch
(fun
(X) when is_number(X) -> X
end)(I))
} || I <- [1, "error"]].
It is also useful to get stack traces. Erlang way is to fail noisy and polite. Give a full information to a programmer but hide from a user.
Erlang has multiple ways to interact with non-Erlang world:
- Start a process outside ERTS(using port). This solution requires to define a protocol and write a driver in your language of choice.
- Run a shell command, something like
os:cmd('ls -al')
. - Run the code inside a virtual machine. This solution also got multiple choices:
- Linked-in drivers. Similar to port, but requires some additional code. It can make a use of additional support like threading and message sending.
- NIF(native implemented functions). Piece of synchronous code, must be small and fast. Like BIFs from standard library.
- C-Nodes. C nodes are nodes implemented in C that obey the Erlang distribution protocol. A “real” distributed Erlang node can talk to a C-node and will think that the C-node is an Erlang node (provided it doesn’t try to do anything fancy on the C-node like sending it Erlang code to execute).