王志軍
王志軍

Reputation: 1021

Convert Erlang catch to Elixir

In Erlang, I can do something like

[catch X+1 || X <- [4,a,6], X > 3].

Get the result,

[5, {‘EXIT’, _}, 7]

Can someone tell me how can I get something similar in Elixir please? I just cannot find the catch in Elixir

UPDATE

After some tries, I think I found the answer.

iex(3)> a = for i <- [4, :a, 6] do
...(3)>   try do
...(3)>     i+1
...(3)>   catch
...(3)>     error, reason ->
...(3)>       {error, reason}
...(3)>   end
...(3)> end
[5, {:error, :badarith}, 7]

Upvotes: 2

Views: 293

Answers (1)

Greg
Greg

Reputation: 8340

Expression catch is an older version of the try expression. It always returns something and catches all exceptions converting them to a term as stated in the documentation:

For exceptions of class error, that is, run-time errors, {'EXIT',{Reason,Stack}} is returned. For exceptions of class exit, that is, the code called exit(Term), {'EXIT',Term} is returned. For exceptions of class throw, that is the code called throw(Term), Term is returned.

It's a construct of the language, its syntax, so would need to be implemented as such in Elixir (i.e. with the same semantic as in Erlang). From the documentation it seems that Elixir only supports the try semantic. The solution you proposed is a good workaround.

Upvotes: 3

Related Questions