I’m using a proprietary library that has an “openConnection” function that I use as such:
conn <- openConnection("user", "pass")
# do some stuff with 'conn' that may return early or throw exceptions
closeConnection(conn)
What’s the R idiom for making sure that the connection gets closed no matter how the current method gets exited. In C++ it would be RAII, in Java it probably would be a “finally” block. What is it in R?
Typically, just a call to
on.exitis used, but you need to do it inside a function.A common case is when you get passed a connection or file name, and you should only create (and close) the connection if you’re given a file name: