[R] tryCatch() and preventing interrupts in 'finally'

Henrik Bengtsson Henrik.Bengtsson at matstat.lu.se
Fri Jun 11 01:03:51 CEST 2004


With tryCatch() it is possible to catch interrupts with tryCatch(). Then you
can use a 'finally' statement to clean up, release resources etc. However,
how can I "protect" against additional interrupts? This is a concern when
the hold down Ctrl+C and generates a sequence of interrupts. Example:

tryCatch({
  cat("Press Ctrl+C...\n");
  Sys.sleep(5);
}, interrupt = function(interrupt) {
  # ...and it will get caught
  cat("Caugh an interrupt:\n");
  print(interrupt);
}, finally = {
  cat("Trying to finalize. Press Ctrl+C...\n");
  Sys.sleep(5);
  cat("...and this line will not be evaluated.\n");
})

Additional tryCatch() inside 'finally' will have the same problem and so.
One idea I had was to wrap up the 'finally' statement in a
withCallingHandlers(, interrupt=...), but it seems that
withCallingHandlers() does not catch interrupts. For example, I tried to
replace 'tryCatch' with 'withCallingHandlers' in the above code.

So, what I basically need is a way to turn off interrupts during the
evaluation of 'finally' or a way for it to restart at the last interrupted
point. Is this possible?

Thanks (again)!

Henrik Bengtsson

Dept. of Mathematical Statistics @ Centre for Mathematical Sciences 
Lund Institute of Technology/Lund University, Sweden (+2h UTC)
+46 46 2229611 (off), +46 708 909208 (cell), +46 46 2224623 (fax)
h b @ m a t h s . l t h . s e, http://www.maths.lth.se/~hb/




More information about the R-help mailing list