views:

397

answers:

2

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

+4  A: 

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:

Shane
Third link is not a link.
Marek
Not Shane's fault -- arguably a bug in the regexp determining how to mark up content on SO.
Dirk Eddelbuettel
+5  A: 

Besides Shane's answer pointing you to other StackOverflow discussions, you could try Google Code Search as e.g. in this query for tryCatch in language=R.

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.

Dirk Eddelbuettel
no disrepect to Shane, but this way to look at examples is awesome. I suffered from a lack of examples. Very helpful.
gappy
Yes, it rocks, and I banged my head hard when I was pointed to it not so long ago. And my most recent query was for ... tryCatch :)
Dirk Eddelbuettel
I feel disrespected! The last time I answer a @gappy question!
Shane
I'd buy you a drink if you'd agreed to come to Chicago this week :)
Dirk Eddelbuettel
Shane, if you come to Chicago you'll drink free all weekend. I guaran-damn-tee it. The offer is good for you too Gappy.
JD Long