user7418039
user7418039

Reputation: 311

Correct syntax to de-omit `try` in Elixir

I'm currently studying Elixir using Elixir official guide. I'm studying error handling part and came across certain part.

Sometimes you may want to wrap the entire body of a function in a try construct, often to guarantee some code will be executed afterwards. In such cases, Elixir allows you to omit the try line:

iex> defmodule RunAfter do
...>   def without_even_trying do
...>     raise "oops"
...>   after
...>     IO.puts "cleaning up!"
...>   end
...> end
iex> RunAfter.without_even_trying
cleaning up!
** (RuntimeError) oops

I'm curious what's the correct syntax if I do not omit try syntax. My best guess so far was like below but it seems like it's not a correct way of doing it.

iex> defmodule RunAfter do
...>   try do 
...>     def without_even_trying do
...>       raise "oops"
...>     end
...>   after
...>      IO.puts "cleaning up!"
...>   end
...> end

Upvotes: 0

Views: 40

Answers (1)

Dogbert
Dogbert

Reputation: 222128

try do ... after ... end should be inside the def:

iex(1)> defmodule RunAfter do
...(1)>   def without_even_trying do
...(1)>     try do
...(1)>       raise "oops"
...(1)>     after
...(1)>       IO.puts "cleaning up!"
...(1)>     end
...(1)>   end
...(1)> end
iex(2)> RunAfter.without_even_trying
cleaning up!
** (RuntimeError) oops
    iex:4: RunAfter.without_even_trying/0

Your second code is also valid, but it'll intercept errors that are thrown while defining the method at compile time:

iex(1)> defmodule RunAfter do
...(1)>   try do
...(1)>     def without_even_trying do
...(1)>       raise "oops"
...(1)>     end
...(1)>     raise "at compile time"
...(1)>   after
...(1)>      IO.puts "cleaning up!"
...(1)>   end
...(1)> end
cleaning up!
** (RuntimeError) at compile time
    iex:6: (module)
iex(1)> RunAfter.without_even_trying
** (UndefinedFunctionError) function RunAfter.without_even_trying/0 is undefined (module RunAfter is not available)
    RunAfter.without_even_trying()

Upvotes: 4

Related Questions