Exception handling in R [closed]

Does anyone have examples/tutorials of exception handling in R? The official documentation is very terse.


Solution 1:

Basically you want to use the tryCatch() function. Look at help("tryCatch") for more details.

Here's a trivial example (keep in mind that you can do whatever you want with an error):

vari <- 1
tryCatch(print("passes"), error = function(e) print(vari), finally=print("finished")) 
tryCatch(stop("fails"), error = function(e) print(vari), finally=print("finished")) 

Have a look at these related questions:

  • Equivalent of "throw" in R
  • catching an error and then branching logic
  • https://stackoverflow.com/search?q=[r]+trycatch

Solution 2:

Besides Shane's answer pointing you to other StackOverflow discussions, you could try a code search feature. This original answer pointed to Google's Code Search has since been discontinued, but you can try

  • Github search as e.g. in this query for tryCatch in language=R;
  • Ohloh/Blackduck Code search eg this query for tryCatch in R files
  • the Debian code search engine on top of the whole Debian archive

Just for the record, there is also try but tryCatch may be preferable. I tried a quick count at Google Code Search but try gets too many false positives for the verb itself -- yet it seems tryCatch is more widely used.