title: Error with on.exit(close(con)) with writeLines()
body: <p>I’m writing a function for writing some information to file. To offer more options for fine control I’m first opening a connection before calling writeLines().
  As it has been stated in many places (eg <a href="https://stackoverflow.com/questions/28300713/how-and-when-should-i-use-on-exit">How and when should I use on.exit?</a>) the function on.exit() may be very helpful to reset settings in case unforeseen events making functions stall.
  I hope you agree, writing files can certainly be considered a somehow risky activity  (eg no more disk space, …).</p>
  <p>So I was thinking of charging on.exit() to make sure the connection gets closed if anything during writeLines() caused my function to stop with an error. However, when I do so I get an error right after writeLines() gets run !
  Has anybody an explanation ?</p>
  <p>The workarounds I found is a) don’t use on.exit() or b) add try(). But I wonder if the second option would realy be helpful if an unforeseen event would make writeLines() stall. Even checking if the connection is still open to avoid closing twice didn't help.</p>
  <p>Surprisingly, so far I couldn't find other examples of people using on.exit() to make sure the current connection gets closed when/after writing text.</p>
  <p>Here an example :</p>
  <pre><code>txt1 &lt;- c(&quot;ABCDEF&quot;,&quot;abcdefgh&quot;)
  
  fxWrite &lt;- function(txt, fileName, opt=0, eol=&quot;\n&quot;) {  
    con &lt;- file(fileName)
    open(con, open=&quot;wb&quot;)
    if(identical(opt,1)) on.exit(try(close(con), silent=TRUE), add=TRUE)
    if(identical(opt,2)) on.exit(close(con), add=TRUE)      # regular on.exit() call
    writeLines(as.character(txt), con=con, sep=eol)
    if(isOpen(con=con)) close(con)
  }
  
  fxWrite(txt1, &quot;test1.txt&quot;, 0)  # no on.exit()
  fxWrite(txt1, &quot;test2.txt&quot;, 1)
  fxWrite(txt1, &quot;test3.txt&quot;, 2)  # regular on.exit(), 
  # with opt=2 the file gets written, BUT : Error in close.connection(con) : invalid connection
  </code></pre>