If you do need to close a connection when a function exists the way to do it is:

on.exit(close(f), add = TRUE)

Which basically adds a statement to a list of statements that will be executed for certain when the function exists (even if an error is thrown)