Julia: How to execute some code on exit of a function? E.g. lik R's `on.exit`?

Viewed 217

I have a piece of code that I run and I want to execute some code on the exit of a function, e.g. to close a connection.

fn(io) = begin
  write(io)
  # do lots of stuff which can fail
  ...
  # want close connection
  on_exit(()->close(io))
end
1 Answers

For this particular example you would probably use a do block:

open("myfile.txt", "w") do io
    write(io, "Hello world!")
end

In the more general case you can use finally. From the docstring:

Run some code when a given block of code exits, regardless of how it exits. For example, here is how we can guarantee that an opened file is closed:

  f = open("file")
  try
      operate_on_file(f)
  finally
      close(f)
  end
Related